Archive for February, 2009

Important examples of Java Generics

Basic:

        List<string> ls1 = new ArrayList</string><string>(); //Create a generic list of strings
        ls1.add("hello");
        ls1.add(new Integer(2)); // no can do, because the type is string
        List<object> ls2 = new ArrayList<string>();
</string></object></string>

Continue »

A Java thread overridding example code

class A implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
 
class B implements Runnable {
 
    public void run() {
        new A().run();
        new Thread(new A(), "name_thread2").run();
        new Thread(new A(), "name_thread3").start();
    }
}
 
public class Main {
 
    public static void main(String[] args) {
        new Thread(new B(), "name_thread1").start();
    }
}

What is the output? Continue »

Fav3

1. Dropbox. “Your files, wherever you need them“. Dropbox is a folder on your computer that gives you access to the latest version of your files from any computer. If you haven’t tried this, I strongly suggest you start using it. It is free for 2GB.

2. A good java studying website: www.javaranch.com. The good thing about this website is its forum, which provide a nice platform for users to communicate. And unlike the code format in the real exam, its code is colored, so it’s comfortable to read. One more good point about it,  is its amount of users. So many people are using it, so you can get info from many people.

3. If you want to link to a specific part of a video on YouTube, you can. For example,

http://www.youtube.com/watch?v=PjDw3azfZWI#t=31m08s

Notice the “#t=31m08s” on the end of the url? That link will take you 31 minutes and 8 seconds into that video. Linking to a particular minute and second can be really helpful — for example, that link takes you straight to where someone asks Eric Schmidt a question about Twitter.

Overriding and overloading in Java with examples

Object type (not the reference variable's type), determines which overridden method is used at runtime
Reference type determines which overloaded method will be used at compile time.
Polymorphism applies to overriding, not to overloading.

Here is an example of overridding. After reading the code, guess the output. Easy!

Continue »

Diagram for Hierarchy of Exception Classes

Any checked exceptions that may be thrown in a method must either be caught or declared in the method’s throws clause. Checked exceptions are so called because both the Java compiler and the Java virtual machine check to make sure this rule is obeyed.

Continue »

FAQ about Web Services and Related Technologies

I got this from JavaRanch, can not hesitate to put it here.

What is a Web Service?

In simple terms a Web Service is an application or business logic that is accessible using standard Internet protocols.

Can I access a web services from any application?

Yes, if your application supports XML based object request and response.

Are there any real web services available for testing?

Yes, check http://xmethods.net/

What is the best Web Service Testing tools?

I would say SoapUI, it is perfectly for installation and implementation. Now if you know some about Web Service, you can start practice with SoupUI and xmethods.net. This can help you understand Web Service.

What are the current free and commercial implementations available for Web Services?

Web Service protocols and supporting package

Web Service protocols and supporting package

Can I access a web service from within a browser?

You can use the JavaScript XmlHttpRequest object (read introductions here and here). You’ll have to create and process the XML requests and responses yourself, though. This works in Internet Explorer, Safari and Mozilla-based browsers like FireFox.

What are the differences between JAX-RPC, JAX-WS, Apache Axis, SAAJ, Apache SOAP, JWSDP, Metro, Jersey and GlassFish?

  • JAX-RPC is a specification/API for Java developers to develop SOAP based interoperable web services. This API is now obsolete, and may be dropped from the next JEE version.
  • JAX-WS is the successor to JAX-RPC. It requires Java 5.0, and is not backwards-compatible to JAX-RPC. This article describes the high-level differences to JAX-RPC.
  • SAAJ is another specification/API for using SOAP envelopes with or without attachments. It operates on a lower level than JAX-RPC or JAX-WS, both of which will use SOAP envelopes based on SAAJ if needed.
  • Apache Axis is an open source implementation of the Java WS APIs for sending and receiving SOAP messages. Axis 1 supports JAX-RPC and SAAJ, while Axis 2 supports SAAJ and JAX-WS.
  • Apache SOAP was the first SOAP implementation. It is now obsolete. It’s better to use Apache Axis to avail oneself of the latest features.
  • Sun JWSDP – Sun Java Webservices Developer Pack, is an implementation of JAX-RPC, SAAJ and various other XML Java technologies. It is now deprecated in favor of GlassFish.
  • GlassFish is the open source reference implementation of J2EE 5. As such, it contains an implementation of JAX-WS.
  • Metro is the web services stack used in GlassFish?. It supports SAAJ, JAX-WS, WS-Security and other standards.
  • Jersey is the reference implementation of the JSR-311 standard for RESTful web services.

What is REST?

Where can I find the relevant standards?


How do I get started building a web service? Show me some code!

Some useful code snippets

  • How can I set HTTP headers like SOAPAction or Basic Authentication in my SOAP request? (link)
  • How can I use HTTP Basic Authentication in my JAX-RPC client? (link)
  • With Axis, how can I access authentication information if I use HTTP Authentication? (link)
  • With Axis, how can I find out which service and operation was invoked? (link)
  • What is the simplest possible Java client for a web service? (link)
  • How do I handle WS-Security UsernameTokens with WSS4J? (link)

What other sources of information are available particularly for Java Web Services?

Which other software packages help implement Java Web Services?

  • Sandesha implements WS-ReliableMessaging
  • BPEL:

More articles on specific topics


Books

Check the JavaRanch Bunkhouse Web Services And SOAP category.

The book title is linked to the publisher where sample content may reside. The ISBN links to Amazon US which tends to list reviews.

SOA Using Java™ Web Services (2007) ISBN 0130449687 Web page Bunkhouse Review

Examines web service technology in a Java EE 5 context as implemented on the Glassfish application server. Covers JAX-WS 2.0 and JAXB 2.0. Mark D. Hansen’s posts during the book promotion. Why is Java Web Services so Hard?

RESTful Web Services (2007) ISBN 0596529260

Explains the principles of REpresentational STate transfer and Resource Oriented Architecture (ROA). Specifies design procedures for resource URIs and resource (state) representations (XML being only one option). Many examples use Ruby but one example does use the Restlet framework. Also looks at AJAX applications as REST clients. Leonard Richardson’s and Sam Ruby’s posts during the book promotion.

J2EE Web Services (2004) ISBN 0321146182 Bunkhouse Review Author’s Blog

Examines web service technology in a J2EE 1.4 context. Covers XML, XML Schema, SOAP 1.1, WSDL 1.1, WS-I Basic Profile 1.0a, UDDI 2.0 as general web service standards and the Java APIs using them: (the now dated) JAX-RPC (incl. EJB endpoints), JAXR (level 0), JAXP, SAAJ, SwA; deployment descriptors are also covered.

Designing Web Services with the J2EE™ 1.4 Platform (2004) ISBN 0321205219 On-line Version PDF Version

A more design/architecture oriented examination of web service technologies in a J2EE 1.4 context.

Service-Oriented Architecture: Concepts, Technology, and Design (2005) ISBN 0131858580 Web page

SOA with SOAP web services explained. Just don’t expect to see any code as this is a platform independent discussion of SOA with SOAP web services.

Service-Oriented Architecture: A Field Guide to Integrating XML and Web Services (2004) ISBN 0131428985 Web page

An examination of how XML technologies, SOAP, WSDL, UDDI, and various WS-* standards can be used to move towards a Service-Oriented Enterprise. No code as this is a platform independent exploration.

SOA Principles of Service Design (2007) ISBN 0132344823 Web page

Service-Orientation isn’t Object-Orientation. Discusses the service design principles needed to develop services that can operate successfully in a SOAP-based SOA.

SOA in Practice: The Art of Distributed System Design (2007) ISBN 0596529554 Web page

Need an SOA instead of a JaBoWS (Just another Bunch of Web Services)? While not specifically written for web service based SOAs but more towards large distributed systems in general this book presents some of the benefits that you can realize by adopting service-orientation and SOA practices. More importantly it reveals that large distributed systems can turn some common sense best practices established for smaller or component-based systems on their heads (example: the perceived need for a common business object model across the entire system). Interview

Java Web Services in a Nutshell

Building Web Services with Java: Making Sense of XML, SOAP, WSDL, and UDDI

Developing Web Services with Apache Axis

Developing Java Web Services: Architecting and Developing Secure Web Services Using Java

Java Web Services Architecture

File Transfer through Java Web Service

I was trying to do a java web service project which allows users to upload files through web service. After searching for several days, I realized that, this is not a good idea. In face, web service can transfer Image from end to end, but not for large regular files, such as pdf, doc, etc. The reason is that server will read file to byte array which consumes much memory. If many users use it at the same time, this may lead to scalability issue.

Continue »

notify() and wait() examples

1. The first one is simple as following:

public class ThreadA {
    public static void main(String[] args){
        ThreadB b = new ThreadB();
        b.start();
 
        synchronized(b){
            try{
                System.out.println("Waiting for b to complete...");
                b.wait();
            }catch(InterruptedException e){e.printStackTrace();}
            System.out.println("Total is: " + b.total);
        }
    }
}
 
class ThreadB extends Thread{
    int total;
    @Override
    public void run(){
        synchronized(this){
            for(int i=0; i<100 ; i++){
                total += i;
            }
            notify();
        }
    }
}

2. The second is more complex, see the comments.

 
import java.util.Vector;
 
class Producer extends Thread {
 
    static final int MAXQUEUE = 5;
    private Vector messages = new Vector();
 
    @Override
    public void run() {
        try {
            while (true) {
                putMessage();
                sleep(5000);
            }
        } catch (InterruptedException e) {
        }
    }
 
    private synchronized void putMessage() throws InterruptedException {
        while (messages.size() == MAXQUEUE) {
            wait();
        }
        messages.addElement(new java.util.Date().toString());
        notify();
        //Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
    }
 
    // Called by Consumer
    public synchronized String getMessage() throws InterruptedException {
        notify();
        while (messages.size() == 0) {
            wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
        }
        String message = (String) messages.firstElement();
        messages.removeElement(message);
        return message;
    }
}
 
class Consumer extends Thread {
 
    Producer producer;
 
    Consumer(Producer p) {
        producer = p;
    }
 
    @Override
    public void run() {
        try {
            while (true) {
                String message = producer.getMessage();
                System.out.println("Got message: " + message);
                //sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String args[]) {
        Producer producer = new Producer();
        producer.start();
        new Consumer(producer).start();
    }
}