Monday, October 23, 2006

Mapping URL to servlet


  • Request URI = context path + servlet path + path info

  • Context Path and Servlet Path start with a / but do not end with it.


Identifying Servlet Path

  1. Exact match of URI to any servlet mapping. In this case, entire match is servlet path and path info is null

  2. Recursive match the longest path by stepping down the request URI path tree to a directory at a time, using / character as a path separator.

  3. last node of request URI contains extension and there exists servlet that handles request for that extension,

  4. forward to default servlet. If no default servlet, send an error message

My Notes for SCWCD


  1. Browser sends web request when
    - user clicks on the hyperlink
    - form post
    - enters address in address bar and press enter

  2. For form data in POST method, enctype attribute should be set as multipart-formdata

  3. Difference between GET and POST on : resource type, type of data,amount of data,visibility and caching

  4. Signature of method doXXXX is protected void and it throws ServletException, IOException

  5. ServletRequest defines getParameter(String Name), getParameterValues(String Name) and getParameterNames() which return String, String[] and Enumeration respectively.

  6. HttpServletRequest defines getHeader(String Name), getHeaders(String Name) and getHeaderNames() which return String, Enumeration and Enumeration respectively.

  7. getWriter on ServletResponse returns PrintWriter object and getOutputStream returns ServletOutputStream(extends OutputStream).

  8. Call to setContentType for setting the mimetype should be done on response object before getWriter or getOutputStream is invoked.

  9. Either getWriter or getOutputStream should be called. Mixing will result in IllegalStateException

  10. setHeader on response object sets the header. setIntHeader and setDateHeader similar functions. addHeader, addIntHeader and addDateHeader sets new value for same header if already exists. containsHeader which returns boolean returns true if the header is already set.

  11. Common headers are : Date, Expires, Last-Modified and Refresh

  12. sendRedirect on response object does a browser redirect. Calling redirect after response is committed (calling flush on writer) will cause IllegalStateException

  13. sendError(int errorcode) will send the error code in response header so that browser can display appropriate message(or web server sends appropriate contents).

  14. ServletContainer loads and instantiates servlet by calling Class.forName(...).new Instance(). To do this there should be a public constructor with no arguments. Having a default class with no constructor or a public class with some constructor having arguments(no default constructor) will error when accessed by client with 500 status.

  15. Two init methods. one takes ServletConfig and the other none. Overriding the one which takes parameter requires a call to super.init to store the config object. instead the GenericServlet's init method which takes parameter makes a call to the no argument init method. So, overriding the no argument init method takes care of everything. To get servletconfig in no arg method call, getServletConfig()

  16. Servlet not initialized at startup to reduce the startup time. However if large initialization is done then the first request for servlet will take long time. To prevent this servlet can be preinitialized at startup by the element in descriptor.

  17. ServletConfig class has getInitParameter and getInitParameterNames which return String and Enumeration respectively. It has getServletContext and getServletName methods.

  18. getResource on ServletContext return java.net.URL. call openStream on URL to get InputStream. Instead call getResourceAsStream to directly get Stream corresponding to resource.

  19. Limitation of getResource is that any URL for any active resource cannot be passed. This will result in security loophole. getResource on jsp file returns the source code of jsp and not the executed output.

Oracle Collections

Good Link for on Oracle collection : http://sheikyerbouti.developpez.com/collections/collections.htm

Thursday, October 19, 2006

Microsoft Fiddler - HTTP Proxy

Installed IE7 and got a good add-on for debugging http traffic. Fiddler Link

Monday, September 25, 2006

Cleared SCJP 5.0 atlast

Cleared SCJP5 today with 91%.

Split Up:
Declarations, Initialization and Scoping - 100
Flow control : 81
API : 100
Concurrency : 87
OO concepts: 90
Collections / Generics : 90
Fundamentals : 90

Sunday, September 24, 2006

finalize method

if in finalized method, there is a call to super(), then handle the throwable in the finalize method of the class, as the finalize of Object class throws Throwable.

synchronized code

synchronization possible on objects only and not on primitives

int x;

synchronized(x) will be compiler error. No autoboxing here...

Assign String to String Buffer

StringBuffer sb = "hello";

this won't compile. StringBuffer have to be explicity created by new operator.

Ambiguous Match

When class implements two or more interface(or extends classes) containing same member varaible type(say, int i). Referencing this variable in the new class will cause ambiguous match for compiler as long as that variable is not redefined in the new class. Redefining the variable in new class will resolve the issue.

Method of private inner class : Accessibility

Not possible to access methods of private inner class as the following code will give compile error.

class MyOuter{
private class MyInner{
public float f(){return 1.2f;}
}
public MyInner getMyInner(){
return new MyInner();
}
}

public class Test13{
public static void main(String... args){
MyOuter o = new MyOuter();
float f = new MyOuter().getMyInner().f();
}
}

Format string conversion

For %b(boolean) : All data types can be passed

For %c(char) : byte, char, short, int

For %d(int) : byte, short, int, long (No char)

For %f(float) : only float and double

For %s(string) : everything

=======================================

public class Test12{
public static void main(String... args){
boolean b = false;
byte by = 2;
char c = 'A';
short s = 7;
int i = 35565;
long l = 2345676436323746l;
float f = 234.567f;
double d = 234.678;
//System.out.printf("%d\t", b);
System.out.printf("%d\t", by);
//System.out.printf("%d\t", c);
System.out.printf("%d\t", s);
System.out.printf("%d\t", i);
System.out.printf("%d\t", l);
//System.out.printf("%d\t", f);
//System.out.printf("%d\t", d);
System.out.println();
System.out.printf("%b\t", b);
System.out.printf("%b\t", by);
System.out.printf("%b\t", c);
System.out.printf("%b\t", s);
System.out.printf("%b\t", i);
System.out.printf("%b\t", l);
System.out.printf("%b\t", f);
System.out.printf("%b\t", d);
System.out.println();
System.out.printf("%s\t", b);
System.out.printf("%s\t", by);
System.out.printf("%s\t", c);
System.out.printf("%s\t", s);
System.out.printf("%s\t", i);
System.out.printf("%s\t", l);
System.out.printf("%s\t", f);
System.out.printf("%s\t", d);
System.out.println();
//System.out.printf("%f\t", b);
//System.out.printf("%f\t", by);
//System.out.printf("%f\t", c);
//System.out.printf("%f\t", s);
//System.out.printf("%f\t", i);
//System.out.printf("%f\t", l);
System.out.printf("%f\t", f);
System.out.printf("%f\t", d);
System.out.println();
//System.out.printf("%c\t", b);
System.out.printf("%c\t", by);
System.out.printf("%c\t", c);
System.out.printf("%c\t", s);
System.out.printf("%c\t", i);
//System.out.printf("%c\t", l);
//System.out.printf("%c\t", f);
//System.out.printf("%c\t", d);
}
}

========================

Output:

2 7 35565 2345676436323746
false true true true true true true true
false 2 A 7 35565 2345676436323746 234.567 234.678
234.567001 234.678000
 A  ?

Saturday, September 23, 2006

OO Encapsulation

Advantages of encapsulation:

  1. Reusability of code

  2. Code Clarity

Friday, September 22, 2006

Some more SCJP5 tips


  1. enum declaration outside class cannot contain static, final or any access modifiers, although enum type is implicity static and final. However enum declaration inside class can be declared as static(although implicitly static) but explicit declaration as final will be compiler error. Explicit declaration of static or final for enums outside class is also compiler error.

  2. Two special cases where primitive == doesn't match the object equals method. NaN and +0.0f with -0.0f. For first case, primitive == is false(so equals will return true) and for second case primitive == is true(so equals will return false).

  3. final instance variables need to get initialized before the constructor ends.(else compiler error).

  4. Protected member inherited to subclass can be accessed in the subclass by a member of declared type as subclass but not by a member of declared type as superclass. Inherited protected member will not be accessible by other classes in the same package of subclass(unless they also extend the subclass).

  5. ArrayStoreException : Storing a object in a array of another object type. E.g., Object[] a = new String[5]; a[0] = new Integer(1); here storing a integer in a array object(whose runtime type is String array causes Heap Pollution).

  6. Compile type determines which overloaded method to be invoked. Run time type determine which overridden method to be invoked.

  7. Constructor is never inherited and hence no overriding. static methods are inherited but can not be overridden.

  8. result of expression is integer. so, byte b = 7+3; will be compile error. Needs explicit cast. However for compound assignment, explicit cast is not required. Thus, byte b = 127; b += 3; will run fine and will give output as -126.

  9. local variable initialization before use. Even null check on a local variable cannot be done before the local variable is initially set as null. Thus, Date d; if(d == null) will cause variable not initialized error. Initialization within if condition or for loop which the compiler is not certain will be executed and then accessing the variable later down the line will also cause variable not initialized error.

  10. When initializing multi-dimension array, the second size can be omitted. However, before assigning the elements into the second dimension array, it has to be initialized with the size of the second dimension. i.e., each of the first dimension array should be assigned a new array object with size specified in the new constructor.

  11. auto-unboxing may result in NPE. e.g., passing wrapper objects to method which expects a primitive and that the wrapper object passed is a instance member variable not initialized.

  12. overloading between methods is fine between one which takes a primitive and other which takes the wrapper of primitive.

  13. In switch statement, case labels should be compile time constants(final variable should be initialized in same line when declared). Duplicate case label will be a compile time error. case label constants should be within the range of the switch argument otherwise compile error.

Wednesday, August 30, 2006

KeepResident plugin for Eclipse/Jdeveloper

Jdeveloper being slow when shifting the application in windows. Reason being the windows swapping the jdeveloper memory even when large amount of physical memory is available.Application has a working set size. The default value is much too small for big Java applications like Eclipse. Hence, windows does a swapping. To prevent this, one thing that can be done is to increase the minimum water mark of this working set size. Then, there is another problem that when the user memory is less than the minimum working set size, windows will think that the application is not used and will do swapping again. Using VirtualLock() will prevent this and force Windows to keep Eclipse in memory.

Got this information from the blog : http://www.orablogs.com/gdavison/archives/001659.html

FAQ on this plugin also provides a clear information : http://suif.stanford.edu/pub/keepresident/faq.html

Thursday, August 24, 2006

SOA Suite - Developer Preview

SOA Suite developer preview is available from : http://www.oracle.com/technology/software/products/ias/soapreview.html

Documentation for SOA, ESB, BPEL available from : http://download-east.oracle.com/otn_hosted_doc/soa/docs/index.htm

WSIF Notes


  1. The Web Services Invocation Framework (WSIF) is a simple Java API for invoking Web services, no matter how or where the services are provided.

  2. WSIF enables developers to interact with abstract representations of Web services through their WSDL descriptions instead of working directly with the Simple Object Access Protocol (SOAP) APIs, which is the usual programming model.

  3. WSIF allows stubless or completely dynamic invocation of a Web service, based upon examination of the meta-data about the service at runtime. It also allows updated implementations of a binding to be plugged into WSIF at runtime, and it allows the calling service to defer choosing a binding until runtime.

  4. The separation of the API from the actual protocol also means you have flexibility - you can switch protocols, location, etc. without having to even recompile your client code.

  5. So if your an externally available SOAP service becomes available as an EJB, you can switch to using RMI/IIOP by just changing the service description (the WSDL), without having to make any modification in applications that use the service.

  6. You can exploit WSDL's extensibility, its capability to offer multiple bindings for the same service, deciding on a binding at runtime, etc.

  7. In the WSDL specification, Web service binding descriptions are extensions to the specification. So the SOAP binding, for example, is one way to expose the abstract functionality (and there could be others). Since WSIF mirrors WSDL very closely, it also views SOAP as just one of several ways you might wish to expose your software's functionality. WSDL thus becomes a normalized description of software, and WSIF is the natural client programming model.

  8. The WSIF API allows clients to invoke services focusing on the abstract service description - the portion of WSDL that covers the port types, operations and message exchanges without referring to real protocols.

  9. The abstract invocations work because they are backed up by protocol-specific pieces of code called providers. A provider is what conducts the actual message exchanges according to the specifics of a particular protocol - for example, the SOAP provider that is packaged with WSIF uses a specific SOAP engine like Axis to do the real work.

  10. The decoupling of the abstract invocation from the real provider that does the work results in a flexible programming model that allows dynamic invocation, late binding, clients being unaware of large scale changes to services - such as service migration, change of protocols, etc.

  11. WSIF also allows new providers to be registered dynamically, so you could enhance your client's capability without ever having to recompile its code or redeploy it.

  12. A provider is a piece of code that supports a WSDL extension and allows invocation of the service through that particular implementation. WSIF providers use the J2SE JAR service provider specification making them discoverable at runtime.

  13. Some bindings for which provider is available : java, ejb, jms, jca

WSDL Notes from W3C Spec


  1. WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information.

  2. Elements in WSDL:

    1. Types - a container for data type definitions using some type system (such as XSD).

    2. Message – an abstract, typed definition of the data being communicated.

    3. Operation – an abstract description of an action supported by the service.

    4. Port Type – an abstract set of operations supported by one or more endpoints.

    5. Binding – a concrete protocol and data format specification for a particular port type.

    6. Port – a single endpoint defined as a combination of a binding and a network address.

    7. Service – a collection of related endpoints.



  3. WSDL doesn't introduce a type definition language. Supports XSD as canonical type system. Allows using other type definition languages via extensibility.

  4. Binding mechanism is used to attach a specific protocol or data format or structure to an abstract message or operation or end point.

  5. It introduces specific binding extensions for the following protocols and message format : SOAP 1.1, HTTP GET/POST, MIME. Other binding extensions can also be used.

  6. Message definitions are always considered to be an abstract definition of the message content. A message binding describes how the abstract content is mapped into a concrete format.

  7. WSDL has four transmission primitives that an endpoint can support:

    1. One-Way:endpoint receives a message.

    2. Request-Response:endpoint receives a message, and sends a correlated message.

    3. Solicit-Response :endpoint sends a message, and receives a correlated message.

    4. Notification : endpoint sends a message.



  8. There may be any number of binding for a port type. A Binding must specify exactly one protocol. Binding must not specify address information.

  9. A port must not specify more than one address. It must not specify any binding information other than address information.

  10. Ports within service have the following relationship:

    1. None of the ports communicate with each other (e.g. the output of one port is not the input of another).

    2. If a service has several ports that share a port type, but employ different bindings or addresses, the ports are alternatives. This allows a consumer of a WSDL document to choose particular port(s) to communicate with based on some criteria (protocol, distance, etc.).



  11. SOAP Binding extends WSDL with the following extension elements:

    1. soap:binding - Signify that the binding is bound to the SOAP protocol format: Envelop, header and body. URI for the transport attribute of this element signifies which transport of SOAP. Can be HTTP, SMTP, FTP etc.,

    2. soap:operation - Required for the HTTP protocol binding of SOAP. For other SOAP protocol bindings, soap:action attribute must not be specified and this attribute may be omitted.

    3. soap:body - specifies how message parts appear inside soap body element. May be abstract schema defintiions or concrete. If abstract, then serialized according to some encoding style. The soap:body element is used in both RPC-oriented and document-oriented messages, but the style of the enclosing operation has important effects on how the Body section is structured:

      1. If the operation style is rpc each part is a parameter or a return value and appears inside a wrapper element within the body

      2. If the operation style is document there are no additional wrappers, and the message parts appear directly under the SOAP Body element.



    4. soap:address - The SOAP address binding is used to give a port an address (a URI). The URI scheme specified for the address must correspond to the transport specified by the soap:binding.




SOAP Message Embedded in HTTP Request
POST /StockQuote HTTP/1.1 
Host: www.stockquoteserver.com
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn
SOAPAction: "Some-URI"

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org

/soap/envelope/"> 
<soapenv:Body>
<m:GetLastTradePrice xmlns:m="Some-URI">
<m:tickerSymbol>DIS</m:tickerSymbol>
</m:GetLastTradePrice>
</soapenv:Body>
</soapenv:Envelope>

SOAP Message Embedded in HTTP Response



HTTP/1.1 200 OK 
Content-Type: text/xml; charset="utf-8"
Content-Length: nnnn

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org

/soap/envelope/"> 
<soapenv:Body>
<m:GetLastTradePriceResponse xmlns:m="Some-URI">
<m:price>34.5</m:price>
</m:GetLastTradePriceResponse>
</soapenv:Body>
</soapenv:Envelope>

Tuesday, August 15, 2006

Accessing class in another class

1.using packaged class in non-packaged or packaged class: Need to use import.

2.using non-packaged class in non-package class : can be present in same directory. Else if different directory, should be available from classpath. No need(and can't) to use import.

3.using non-packaged class in packaged class: not possible at all(since the non-packaged class name mentioned in packaged class will be interpreted as belonging to the pacakged class's package and so the compiler will take this class as package.class and so will report wrong class file.

Wednesday, June 21, 2006

Multiple DTD in xml and namespace workaround in DTD

Following xml fragments will give an idea of how to use multiple dtd's in xml and also the workaround of specifying namespace in dtd

File : s.dtd
============
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT computer (ns1:address) >
<!ELEMENT ns1:address (type, ipaddress)>
<!ELEMENT type (#PCDATA)>
<!ELEMENT ipaddress (#PCDATA)>

File : s1.dtd
==============
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT ns2:student (name, ns2:address, computer) >
<!ATTLIST ns2:student xmlns:ns2 CDATA #FIXED "http://krishna/ns2">
<!ELEMENT ns2:address (#PCDATA) >
<!ELEMENT name (#PCDATA) >

File:student.xml
================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ns2:student SYSTEM "s1.dtd" [<!ENTITY % s SYSTEM "s.dtd">
%s;
]>
<ns2:student xmlns:ns2="http://krishna/ns2">
<name >krishna</name>
<ns2:address>unknown</ns2:address>
<computer>
<ns1:address>
<type></type>
<ipaddress></ipaddress>
</ns1:address>
</computer>
</ns2:student>

Monday, June 19, 2006

Anonymous array declaration

Anonymous arrays have to be assigned to the variables at the time of declaration of varaible itself. Assigning to the variable after variable declaration is not possible
ie.,
int[] i = {1,2,3} is fine.
But,
int[] i;
i = {1,2,3} is compiler error.
This restriction at the time of method invocation is valid, since we don't know the type of array(overloading issue). But for assignment the left side variable type is known. So, why should it be not possible to cast the anonymous array {1,2,3} to int[] and assign to variable.