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.

Sunday, June 18, 2006

i=i++ produces the output "0" instead of "1".

The code
int i = 0;
i = i++;
System.out.println(i);
produces the output "0" instead of "1".

"i = i++" roughly translates to

int oldValue = i;
i = i + 1;
i = oldValue;

Are string literals garbage collected?

The answer is no. String class maintain a list of references to string(in heap) in the constant pool. When new is used to create string, then a new string object is created in heap and the reference to this object is returned to the code. Thus, we will have two string objects. If intern() method is called on this object, then the reference to the other string object(whose reference is maintained in literal pool) is returned to the code and the string object created using new will be garbage collected. Even when there are no references to the string literal object, string literal will not be garbage collected, because the reference to this object is still maintained in the string literal pool

Saturday, June 17, 2006

My Notes from JLS 3.0

Lexical Structure
1. Legal code point is U+0000 to U+10FFFF. Code points greater than U+FFFF are supplementary characters. Supplementary characters are stored as pairs of two 16-bit code units. (High Surrogate range: U+DB80 to U+DBFF and Low Surrogate Range : U+DC00 to U+DFFF).
2. Line Terminator is the ASCII character CR(“return”) followed by LF(“new line”).
3. Input Elements are : Whitespace(space, horizontal tab, form feed), comment(/* .. */ and //) and token(Identifiers, keyword, literal, separator and operator).
4. Comments do not nest.(/* and */ do not have special meaning inside // and // has no special meaning in comments that begin with /* or /**).
5. Identifier : Identifierchars but not a keyword or BooleanLiteral or NullLiteral).
6. Identifiers begin with JavaLetter(Character.isJavaIdentifierStart(int)) followed by JavaLetterOrDigit(Character.isJavaIdentifierPart(int)).
7. Literals : Integer(Decimal, octal and hexadecimal), Floating point(decimal or hexadecimal), Boolean(true & false), Character, String and Null literal.
8. This assignment String s1 = "\u000a"; will cause compiler error. Because \u000a is line feed character. Hence, within string literal to use line feed use “\n”
9. Literal Strings refer to the same string object. Strings computed by constant expressions are computed at compile time and then treated as if they are literals. String hello = "Hello", lo = "lo"; ((hello == ("Hel"+"lo")) is true.
10. Strings computed by concatenation at run time are newly created and therefore distinct. Thus, (hello == “Hel” + lo) will be false.
11. Escape sequence : b,t,n,f, r, “,’,\ and octal escape( \ followed by one to three octal digits).

Types, Values and Variables
1. Strongly Typed language: Every variable and every expression has a type that is known at compile time.
2. Integer operators throw NPE if unboxing conversion of a null reference is required. In divide and remainder operator, they throw Arithmetic exception, if right-hand operator is zero. OutofMemoryError in case of ++ and – if boxing conversion is required and there is not sufficient memory for conversion.
3. Floating Point : Positive zero and negative zero compare equal.
4. NaN is unordered, so the numerical comparison operators <, <=, >, >= return false if either or both the operands are NaN. Equality operator returns false if either operand is NaN. Inequality operator return true if either operand is NaN.
5. The language uses round toward zero when converting a floating value to an integer
6. An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result.
7. Heap pollution : List l = new ArrayList(); List ls = l; // unchecked warning. Heap pollution arises, as the variable ls, declared to be a List, refers to a value that is not in fact a List.

Conversions and Promotions
1. Five Conversion Contexts : Assignment Conversions, Method Invocation Conversions, Casting conversion, String conversion, Numeric conversion
2. 11 Conversion categories : Identity conversion, Widening primitive conversion, Narrowing Primitive Conversion, Widening and Narrowing primitive conversion, widening reference conversion, narrowing reference conversion, boxing conversion, Unboxing conversion, Unchecked conversion(raw type to generic type), capture conversion
3. Narrowing primitive conversion : short to char is also narrowing primitive conversion(cause char is unsigned while short is signed. So short to char loses precision).
4. Widening and Narrowing primitive conversion : byte to char. Here byte is first widened to int and then narrowed to char
5. Assignment Conversions allows the following: identity, widening primitive, widening reference, boxing, unboxing.
6. If the expression is a constant expression of type byte, short, char or int:
a. Narrowing primitive conversion if type of variable is byte, short or char and the value of constant expression is representable in the type of variable.
b. Narrowing primitive conversion followed by boxing conversion if type of variable is Byte, Short or Character and the value of constant expression is representable in byte, short or char respectively.
7. Implicit narrowing of integer constants is not available in Method invocation conversions. (Reason being it will add complexity to the overloaded method resolution process).

Names
1. Obscured declarations : a simple name may occur in contexts where it may potentially be interpreted as the name of variable, type or package. In this case, variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.
2. Members of package : sub package, top level class types and top level interface types
3. Members of class type : classes, interface, fields and methods.
4. A class or interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error.
5. Members of array type : public final field length, public method clone and members inherited from Object(except method clone).

Packages
1. A package may not contain two members of the same name, or a compile-time error results.
2. package names mightg contain Unicode characters. If the host OS doesn’t support Unicode characters(\uxxxx) in their file system name, then the file name can be named by replacing the unicode characters as @xxxx. Java will map the Unicode character(\uxxxx) to the letters @xxxx in the file name.
3. An implementation of the Java platform must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.
4. In implementations of the Java platform that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is observable at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.

Classes
1. Newly declared fields can hide fields declared in a superclass or superinterface.
2. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.
3. A compile-time error occurs if a class has the same simple name as any of its enclosing classes or interfaces.
4. Enum types must not be declared abstract; doing so will result in a compile-time error.
5. It is a compile-time error for an enum type E to have an abstract method m as a member unless E has one or more enum constants, and all of E's enum constants have class bodies that provide concrete implementations of m.
6. It is a compile-time error for the class body of an enum constant to declare an abstract method.
7. Inner classes may not declare static initializers or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields.
8. Member interfaces (§8.5) are always implicitly static so they are never considered to be inner classes.
9. When an inner class refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used. A blank final (§4.12.4) field of a lexically enclosing class may not be assigned within an inner class.
10. It is a compile-time error if the evaluation of a variable initializer for a static field of a named class (or of an interface) can complete abruptly with a checked exception
11. The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
a. The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
b. The usage is not on the left hand side of an assignment.
c. The usage is via a simple name.
d. C is the innermost class or interface enclosing the usage.

Interfaces
1. It is a compile-time error to refer to a type parameter of an interface I anywhere in the declaration of a field or type member of I.
2. All interface members are implicitly public. They are accessible outside the package where the interface is declared if the interface is also declared public or protected,
3. If the interface declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superinterfaces of the interface.
4. It is a compile-time error for the body of an interface declaration to declare two fields with the same name.
5. A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface.
6. If the keyword this or the keyword super occurs in an initialization expression for a field of an interface, then unless the occurrence is within the body of an anonymous class, a compile-time error occurs.
7. A method declared in an interface must not be declared strictfp or native or synchronized, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties.
8. It is a compile-time error if an annotation type T contains an element of type T, either directly or indirectly.

Arrays
1. Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion and become int values.
2. An attempt to access an array component with a long index value results in a compile-time error.
3. All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.
4. ArrayStoreException : An assignment to an element of an array whose type is A[], where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A.

Exceptions
1. If a try or catch block in a try-finally or try-catch-finally statement completes abruptly, then the finally clause is executed during propagation of the exception, even if no matching catch clause is ultimately found. If a finally clause is executed because of abrupt completion of a try block and the finally clause itself completes abruptly, then the reason for the abrupt completion of the try block is discarded and the new reason for abrupt completion is propagated from there.