Thursday, December 28, 2006

EJB Lookup

1. When deploying EJB, it has a name(if specified using annotation : @Stateless(name="SessionEJB") or if descriptor: <ejb-name>SessionEJB</ejb-name>.

2. This EJB deployed to OC4J. Now to do a lookup for this EJB, we can use either ApplicationClientInitialContextFactory or RMIInitialContextFactory.

3. In case of RMIInitialContextFactory, no need of application-client.xml and the context lookup will be : new InitialContext.lookup("SessionEJB").

4. In case of ApplicationClientInitialContextFactory, we need application-client.xml. It has to introduce the ejb refrence going to be used in code as:

<application-client xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application-client_1_4.xsd" version="1.4" xmlns="http://java.sun.com/xml/ns/j2ee">
<display-name>InterceptorTest-app-client</display-name>
<ejb-ref>
<ejb-ref-name>ejb/SessionEJB</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<remote>myEJB.SessionEJB</remote>
<ejb-link>SessionEJB</ejb-link>
</ejb-ref>
</application-client>

5. Here, ejb-link is used to link to the actual bean. Now, in the client code we use the ejb-ref-name for lookup as:

new InitialContext().lookup("java:comp/env/ejb/SessionEJB");

Sunday, December 24, 2006

MDB deployment in OC4J

1. Create the MDB(normal java class with @MessageDriven annotation). Set the ActivationConfigs.

@MessageDriven(
activationConfig = {
@ActivationConfigProperty(propertyName="connectionFactoryJndiName", propertyValue="jms/TopicConnectionFactory"),
@ActivationConfigProperty(propertyName="destinationName",
propertyValue="jms/demoTopic"),
@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Topic"),
@ActivationConfigProperty(propertyName="messageSelector", propertyValue="RECIPIENT = 'MDB'") } )

2. Create EJB jar deployment profile(MDBServer.deploy) for the above MDB and deploy it to OC4J server(application name = MDBServer)

3. In same project, create the MDBClient. Inject the resources @Resource(name="jms/demoQueue") and @Resource(name="jms/TopicConnectionFactory"). Use connectionFactory and create connection, then session, message and send the message using producer.

4. In Jdeveloper create jndi.properties file with:

java.naming.factory.initial= oracle.j2ee.naming.ApplicationClientInitialContextFactory
java.naming.provider.url=ormi://localhost:23791/MDBServer
java.naming.security.principal=oc4jadmin
java.naming.security.credentials=welcome

5. Create client Jar deployment profile from Jdeveloper. This creates application-client.xml. Modify application-client.xml and add following lines for the resource reference entries(Make sure to mention the main class file name in descriptor creation)

<application-client xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/application-client_1_4.xsd" version="1.4" xmlns="http://java.sun.com/xml/ns/j2ee">
<display-name>MDB1-app-client</display-name>
<resource-env-ref>
<resource-env-ref-name>jms/demoTopic</resource-env-ref-name>
<resource-env-ref-type>javax.jms.Topic</resource-env-ref-type>
</resource-env-ref>
<resource-env-ref>
<resource-env-ref-name>jms/TopicConnectionFactory </resource-env-ref-name>
<resource-env-ref-type>javax.jms.TopicConnectionFactory </resource-env-ref-type>
</resource-env-ref>
</application-client>

6. Deploy the deployment profile MDBClient.deploy to MDBClient.jar.

7. From command prompt containing the jar file, set class path and run :

D:\installs\JdevStudio10131\jdev\mywork\MDB\MDB1\deploy>set CLASSPATH =.\;D:\installs\oc4j\j2ee\home\oc4jclient.jar;D:\installs\oc4j\j2ee\home\lib\javax77.jar;

D:\installs\JdevStudio10131\jdev\mywork\MDB\MDB1\deploy>java oracle.oc4j.appclient.AppClientContainer MDBClient.jar

Output from the application server log will contain:

06/12/24 20:26:44 onMessage() - Message[ID:Oc4jJMS.Message.krishnamoorthy.64e0c3
ab:10fb4f6b670:-8000.4]

onMessage method of the MDB just does a system.out.println(message)

Note: Without creating jar of client files and if I directly run using:

D:\installs\JdevStudio10131\jdev\mywork\MDB\MDB1\classes>java -Djava.naming.factory.initial=oracle.j2ee.naming.ApplicationClientInitialContextFactory -Djava.naming.provider.url=ormi://localhost:23791/MDBServer -Djava.naming.security.principal=oc4jadmin -Djava.naming.security.credentials=welcome myJMSClient.TestJMSClient

I get

Exception in thread "main" java.lang.NullPointerException
at myJMSClient.TestJMSClient.main(TestJMSClient.java:22)

So, should a JMS client be run always using AppClientContainer as :

java oracle.oc4j.appclient.AppClientContainer MDBClient.jar

Friday, December 22, 2006

Running EJB Client Standalone

HelloWorld.java

package myEJB;

import javax.ejb.Remote;

@Remote
public interface HelloWorld {
public String sayHello(String name);
}

HelloWorldBean.java

package myEJB;

import javax.ejb.Stateless;

@Stateless
public class HelloWorldBean implements HelloWorld {
private int count;

public String sayHello(String name) {
count++;
System.out.println("sayHello method from Bean ");
return "Hello " + name + " Count : " + count;
}
}

Compile the classes and run in embedded oc4j of jdeveloper. Or create a ejb jar deployment profile and deploy it to standalone oc4j server. Deployment name is the application name in the standalone oc4j. Let us say application is HelloWorldDeploy. Ear file contains jar file and META-INF. Inside META-INF is the application.xml containing the name of ejb module jar file. Jar file contains the interface and bean classes. After deploying, create a test client as follows:

HelloWorldClient.java

package myEJB;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class HelloWorldClient {
public static void main(String [] args) {
try {
final Context context = new InitialContext();
HelloWorld helloWorld = (HelloWorld)context.lookup("java:comp/env/ejb/HelloWorldBean");
// Call any of the Remote methods below to access the EJB
System.out.println(helloWorld.sayHello( "Krishna" ));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

To invoke ejb method from command line:

D:\work\MyWork\ejb\ejb3>set CLASSPATH=D:\installs\JdevStudio10131\j2ee\home\oc4jclient.jar;.\;

D:\work\MyWork\ejb\ejb3>java -Djava.naming.factory.initial=oracle.j2ee.naming.Ap
plicationClientInitialContextFactory -Djava.naming.provider.url=ormi://localhost
:23791/HelloWorldDeploy -Djava.naming.security.principal=oc4jadmin -Djava.naming
.security.credentials=welcome myEJB.HelloWorldClient

Output is : Hello Krishna Count : 1

Thursday, December 21, 2006

Transaction Isolation Level

Good link for getting a refresh on the isolation level: http://www.oracle.com/technology/oramag/oracle/05-nov/o65asktom.html
Oracle supports READ COMMITTED and SERIALIZABLE. Oracle doesn't allow dirty reads(READ UNCOMMITTED). It allows a third isolation level which is READ ONLY. No insert, update, delete can be done in this mode.

Wednesday, December 20, 2006

RMI tutorial on SUN

1. Start the rmiregistry at the default port 1099. (rmiregistry.exe)

2. Start the Local Http server for delivering class files between server-RMI and RMI-Client.

D:\work\MyWork\rmi\suntutorial>java examples.classServer.ClassFileServer 1185 D:\work\MyWork\rmi\suntutorial

3. Then start the ComputeEngine server using :

D:\work\MyWork\rmi\suntutorial>java -cp .\;compute.jar -Djava.rmi.server.codebase=http://pc-krsethur-in:1185/ -Djava.rmi.server.hostname=pc-krsethur-in -Djava.security.policy=D:\work\MyWork\rmi\suntutorial\server.policy engine.ComputeEngine

4. Remove the client files from the suntutorial folder and place it in a folder named test under this suntutorial so that RMI will get the files using http from the client(thus, the above classpath doesn't include the client classes).

5. server.policy should have the line

grant {
permission java.net.SocketPermission "*:*", "listen,accept,connect";
};

for the binding of remote object to the registry(1099).

6. Now run the client as

D:\work\MyWork\rmi\suntutorial\test>java -cp .\;..\compute.jar; -Djava.rmi.server.codebase=http://pc-krsethur-in:1185/test/ -Djava.security.policy=D:\work\MyWork\rmi\suntutorial\client.policy client.ComputePi pc-krsethur-in 45

Output
3.141592653589793238462643383279502884197169399

7. Client.policy should have similar line above(5)

8. here -Djava.rmi.server.codebase=http://pc-krsethur-in:1185/test/ will be set because during client execution, we call executeTask on the proxy remote object. The remote object running in the RMI runtime will delegate to the task object. Now, the task object is still not present in the RMI runtime and will give class not found exception. To prevent that we set the codebase to http://pc-krsethur-in:1185/test/. Here pc-krsethur-in:1185 will deliver files present under D:\work\MyWork\rmi\suntutorial. However, the task class is present in D:\work\MyWork\rmi\suntutorial\test folder. Hence, we append the test/ in the URL for the codebase. Our local file server will serve the classes from D:\work\MyWork\rmi\suntutorial\test for RMI runtime during client execution. Similarly, when the server was started, during binding of remote object, the interface classes(Compute.class and Task.class) for the RMI runtime was served by -Djava.rmi.server.codebase=http://pc-krsethur-in:1185/.

9. After a single execution of both server and client, the classes(Compute.class and Task.class) for the server execution and the class(Task.class) from client execution will be present in the RMI runtime and hence if the local file server is stopped at this time and the server is aborted and restarted, it will work fine without any error about class not found. Similarly if the client is run now also, the client will work fine, because the Task.class is already loaded in the RMI runtime.

10. Now if we stop the rmiregistry.exe(thus all the classes loaded in RMI runtime are gone) and restart the rmiregistry and then start the server or client(with the local file server stopped), they will fail with class not found exception.

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.

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.

Tuesday, June 13, 2006

Uninstalling Oracle 10g Manually from Windows XP

List of additional steps to do for cleaning the system completely after uninstall using universal installer.
# Stop any Oracle services that have been left running.
Start->Settings->Control Panel->Services
Look for any services with names starting with 'Oracle' and stop them.
# Run regedit and delete the following keys (some may have slightly different names in your registry):
HKEY_CURRENT_USER\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\EventLog\Application\Oracle.oracle
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\OracleDBConsole
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\Oracle10g_home
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\OraclService
Note that the services control panel will still show the old services until you reboot.
# Delete the Oracle home directory
C:\Oracle
# Delete the Oracle Program Files directory:
C:\Program Files\Oracle
# Delete the Oracle Start Menu shortcuts directory:
C:\Documents and Settings\All Users\Start Menu\Programs\Oracle*
Where * indicates the name of your install. Look for and remove all Oracle directories from that location.
# Remove Oracle refereces from the path. To edit your path go to:
Start->Settings->Control Panel->System->Advanced->Environment Variables
Edit both of the environment variables user PATH and system PATH. Remove any Oracle references in them.
# Remove Oracle.DataAccess and any Polic.Oracle files from the GAC which is at:
C:\Windows\assembly\

Monday, June 12, 2006

Extending Inner Class

Another good thread from javaranch.

class A{}
class B extends A{
public static void main(String args[]){
B b=new B(); // Line 1
}
}

At line 1, basically two objects are created.

First of class A, then of class B. So basically we have two instances here and instance of A act as a subobject which is actually wrapped within intstance of subclass. So, when extending the inner class, an instance of InheritInner must have an instance of Inner class and Inner class always require an instance of Outer class. So, to the constructor of InheritInner which extends Outer.Inner we must also pass the enclosing outer instance of inner class and call the super constructor of enclosing outer instance which will take care of instantiating the inner instance.


class Outer {class Inner {}}

public class InheritInner extends Outer.Inner {
InheritInner(Outer o) {
o.super();
}
public static void main (String[] args){
Outer o = new Outer();
InheritInner ii = new InheritInner(o);
}
}

If the inner class was static(nested class), then calling o.super() is not required, since the inner class will be instantiated without an enclosing outer class instance.

Sunday, June 11, 2006

Learnings from javaranch

1. Unreachable statement compile error is only for the loop statements(while) and not for conditional statement(if). while(false){..} will cause code not reachable error. But if(false){..} will not cause error. the conditions of course should be compile time constants.

2. "final variable in for loop". for(final int i:some iterable){print i..} will not error because the enhanced for loop is rewritten in basic for loop as for(int j=0; i < iterator.count;j++){final int i = iterator.next()...} so, the scope of variable is within one loop of the for. Instead within the for loop, if we tried to modify the final variable, it will error.

3. static variable and static fields are initialized in the order in which they are declared. so in the static block if we assign a variable which is declared down the line to another variable it will error. However this doesn't hold good for static methods. In the static methods, the variable which are declared down the line can be still be accessed and assigned to. Issue only for static initializers.

4. Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals. Strings computed by concatenation at run time are newly created and therefore distinct.

5. a private method in super class and same method name in child class. If some other method in parent class invoked by the child object calls the private method, it is the private method of the super class which is called and not the polymorphic method in child. polymorphic invocation doesn't apply if the super class method is private.

Saturday, June 10, 2006

Java Thread : notify and notifyAll

Had this question : "notify results in a single thread acquiring a lock whereas notifyAll results in all the threads competing for the lock and one of them acquiring it so any way only one thread is able to acquire the lock, so why do we need notfyAll at all."
The answer lies in : Even though in the first case only one thread gets the lock, the problem occurs in that there may be no other threads to notify the other threads which called wait() earlier. So, if we call notifyAll, all the threads will be waken up and will be competing for the lock. So, to compete for the lock, first step is to get woken up by getting a notification from another thread that is going to release the lock.

Got the above content from this link

Saturday, June 03, 2006

Resulting type in conditional operator

If one expression is a primitive type and the other can be unboxed to become a compatible primitive type, then the unboxing occurs and the expressions are reconsidered.

If both expressions are numeric primitive types then the resulting type is also a numeric primitive type, obtained by numeric promotion if needed.

If one expression is an int constant, and the other is byte, short, or char, and the int value can fit in the smaller type, then the resulting type is that smaller type.

If one of the expressions is a primitive type and the other is a reference type that can't be unboxed to get a compatible value, or both expressions are primitive but incompatible, then the primitive type is boxed so that we have two reference types.

Given two reference types that are different, the type of the expression is the first common parent type. For example, if both expressions were unrelated class types that implemented Cloneable then Cloneable would be the type of the expression; if one expression was int while the other was String, then Object would be the resulting type.

Widen, boxing, varargs

widen and then boxing not allowed. But widen and then var-args allowed. This will
be the last priority match. Boxing and then widen will win over widen and then var-args.

Implicit casting of primitives

Implicit casting of primitives happens only in assignment and not in method argument passing.
Short s = 7;(fine)
public void junk(short s){} and junk(7) will error. This is fine because in former case, we know the target type to which the casting is to be done. But in the latter case we don't know the target type to be casted to(in case there are multiple overloaded junk methods).

Widening Wins Boxing when alone: Causes confusion combined with Var-args

For the following methods:
public void test(long... l)
{
System.out.println("Widen varargs");
}
public void test(Integer... i)
{
System.out.println("Boxed and vararg'ed");
}
invocation of int i =5; test(i) will cause confusion to compiler. However if the methods are changed from varargs to normal parameters(long and Integer), then widening method will win over the Boxing parameter method. So, widening wins boxing when alone. But not when combined with var-args.

Wednesday, May 31, 2006

About Integrated Windows Authentication in IIS

Did a telnet to localhost to get /localstart.asp which is protected by Integrated windows authentication. Response HTTP header is :
HTTP/1.1 401 Access Denied
Server: Microsoft-IIS/5.1
Date: Wed, 31 May 2006 04:09:56 GMT
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
Content-Length: 4431
Content-Type: text/html

Now, the browser is required to authenticate using NTLM. This mode is supported only in IE. So, the same page(localstart.asp) when opened using firebox will retry sending username/password from the popup and will fail. Whereas In IE, it will render the page properly. So, to view the localstart.asp page in browsers other than IE, we can't use Integrated windows authentication. Rather we may use Basic authentication. HTTP Response headers in case of basic authentication:
HTTP/1.1 401 Access Denied
Server: Microsoft-IIS/5.1
Date: Wed, 31 May 2006 04:14:47 GMT
WWW-Authenticate: Basic realm="APPLICATIONS"
Content-Length: 4431
Content-Type: text/html

My horrible experience with IIS

Tried installing IIS in my XP Pro. After install, initially the localstart.asp is erroring out with HTTP 500 server error. Resolution :
------------------------------------------------------------------------------------
Please make sure that anonymous authentication is not selected for the localstart.asp file as per the instructions in KB Article 251361.
http://support.microsoft.com/default.aspx?scid=kb;EN-US;q251361
It does not matter if you are logged on as administrator or not. The RFC says that the client is supposed to try anonymous authentication first, which the client does. If this authentication method is supported (enabled), the client has no reason to try to authenticate, and the anonymous user account specified on the server will be used to run the ASP file. This user account does not have permissions to the metabase, hence it fails with this error message.
------------------------------------------------------------------------------------
So, I unchecked the unanonymous access checkbox. After this I get the HTTP 401.2 unauthorized: Logon. Searched google and found some solutions relating to excluding the localhost from the exceptions list in proxy, adding the webserver program in the windows firewall list. These two solutions didn't work. Solution is that atleast one type of authentication method should have been used :
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q253667&sd=tech
Then I used the checkbox "Integrated Windows Authentication". Issue got resolved. Probably a good documentation for IIS was missing or I didn't search properly...

Thursday, May 25, 2006

Overloading with var-args: ambiguous match

package junk;

public class Test8{
public static void print(String title) {
System.out.println("first print");
}
public static void print(String title, String... messages) {
System.out.println("second print");
}
public static void print(String... messages) {
System.out.println("third print");
}
public static void main(String... args)
{
print("Hello");
print("Hello", "Krishna");
print("Hello", new String[]{"Krishna"});
print(new String[]{"Hello", "Krishna"});
}
}

Output:
reference to print is ambiguous, both method print(java.lang.String,java.lang.String...) in junk.Test8 and method print(java.lang.String...) in junk.Test8 match

Does static initializers loop infinitely if they reference each other in the initialization code?

package junk;

public class Test7{
public static void main(String... args)
{
System.out.println("x.i = " + X.i);
System.out.println("x.j = " + Y.j);
System.out.println("y.i = " + X.i);
System.out.println("y.j = " + Y.j);
}
}

class X{
static int i=1;
static int j=2;
static{
System.out.println("X static : before calling Y");
i = Y.i;
System.out.println("X static : after calling Y");
}
static{
System.out.println("next static block in X : start");
j = Y.j;
System.out.println("next static block in X : end");
}
}

class Y{
static int i=3;
static int j=4;
static{
System.out.println("Y static : before calling X");
i = X.i;
System.out.println("Y static : after calling X");
}
static{
System.out.println("next static block in Y : start");
j = X.j;
System.out.println("next static block in Y : end");
}
}

output:
X static : before calling Y
Y static : before calling X
Y static : after calling X
next static block in Y : start
next static block in Y : end
X static : after calling Y
next static block in X : start
next static block in X : end
x.i = 1
x.j = 2
y.i = 1
y.j = 2

Wednesday, May 10, 2006

Monday, April 24, 2006

Windows XP : To find services associated to OS process

Was finding a lot of svchost.exe process getting lauched. To find out the services for each of the scvhost process, following command was helpful.
D:\>tasklist /svc

Image Name PID Services
========================= ====== =============================================
System Idle Process 0 N/A
System 4 N/A
smss.exe 820 N/A
csrss.exe 892 N/A
winlogon.exe 920 N/A
services.exe 976 Eventlog, PlugPlay
lsass.exe 988 Netlogon, PolicyAgent, ProtectedStorage,
SamSs
svchost.exe 1152 DcomLaunch, TermService
svchost.exe 1240 RpcSs
svchost.exe 1376 AudioSrv, CryptSvc, Dhcp, dmserver, ERSvc,
EventSystem, helpsvc, HidServ, lanmanserver,
lanmanworkstation, Messenger, Netman, Nla,
Schedule, seclogon, SENS, SharedAccess,
ShellHWDetection, Themes, TrkWks, W32Time,
winmgmt, wuauserv, WZCSVC
svchost.exe 1428 Dnscache
svchost.exe 1616 LmHosts, RemoteRegistry, SSDPSRV, WebClient
spoolsv.exe 1784 Spooler

Thursday, April 20, 2006

Managing state in SOA

A good link on managing state in SOA. Some of the key points:
1. To Manage conversation state, a state identifier needs to maintain following information w.r.t each request-response interaction
  1. Unique identifier of the Web service client

  2. Identifier of the Web service conversation originated for that client

  3. Identifier of the service request within that conversation

  4. Indicator of the conversation phase between the service requester (client) and service provider (Starting, Continuing, and Ending), which is used by the service for proper state maintenance

  5. Indicator of the interaction status between the service distribution function of the Web services infrastructure and the invocation interface (very helpful in dynamic invocations with late-binding of Web service interfaces)


2. This identifier information can be passed in three ways:
* Pass the identifier information as an extra parameter in the Web service method; the Web service interface can be designed to accept not only the XML document message, but also to accept additional parameters that represent the state identifier information.
* Pass the identifier information as a part of the XML document—the XML document can contain such information embedded within its body.
* Pass the identifier information in the SOAP message header.
3. First two methods are not preferred as code becomes harder to maintain.
4. Three-step development process:
1. Design and code the basic service components.
2. Develop SOAP message handlers.
3. Construct Web services (expose) out of developed J2EE components.
5. SOAP handlers are for: to handle the insertion of state qualifiers into the standard SOAP message definition. In JAX-RPC services, a handler is represented by a handler class that implements handleRequest() and handleResponse() methods for modifying the request and response message.
6. Create Handlers implementing javax.xml.rpc.handler.Handler and implementing the handleRequest method. The javax.xml.soap.SOAPMessage class is used by the handler to manipulate the SOAP message. A SOAPMessage object contains a SOAPPart object that contains the actual SOAP XML document and a SOAPEnvelope object that is "decomposed" to access SOAP body and header.
7. Get a SoapFactory instance and createElement using it. To the element addTextNode. Finally construct WS using handlers and deploy to AS.

Thursday, April 13, 2006

Checklist for buying flat from builder


  1. Original copy of your agreement with the builder

  2. 7/12 extract or property register card of the land under construction

  3. Index II extract of your agreement with the builder

  4. Copy of N.A.(Non Agricultural) permission for the land from the collector

  5. Search and title report (with the details of documents) for the last 30 years

  6. Development agreement between the owner of land and the builder

  7. Copy of order under the Urban land Ceiling Act

  8. Copy of building plans sanctioned by the competent authority

  9. Commencement certificate granted by Corporation / Nagar Palika

  10. Building completion certificate (if available)

  11. The latest receipts of taxes paid

  12. Partnership deed or memorandum of association of the builders firm

Wednesday, April 12, 2006

CheckList for purchasing new flat

1. Conveyance / Sale deed : Document by which the title of a property is conveyed by the seller to the purchaser
2. ULC [Urban Land (Ceiling & Regulation) Act] :
3. 7/12 extract is a document, which shows the names of the owners of the property. It contains details such as the Survey numbers, area, date from which the current owner's names were registered as owners. The 7/12 extract is issued by the Tehsildar or the concerned land authorities.
4. Index II - Index II is a document issued by the office of the Sub- Registrar of Assurances. It mainly mentions the names of the sellers & purchasers of a property for which the document is registered.
5. Search report & Title certificate - A Title certificate is issued by an advocate after conducting a search of the title of the property, which is intended to be purchased. The title certificate would state if the property is unencumbered and has a clear marketable title.(30 years)
6. Non Agricultural (N.A) permission --
7. Development Agreement : entered into by the builder with the landowner. It contains details regarding the terms and conditions on which the landowner has permitted development of his property. This is where the landowner engages a third party (i.e. the developer) to develop and build on their plot of land. This agreement is generally accompanied by a Power of Attorney in favour of the developer.
8. Approved building plans need to be checked necessarily. The plans must be approved by the Municipal Corporation/ Town Planning authority or other concerned authorities like CIDCO, MHADA, HUDCO, Gram Panchayat, etc. as applicable depending on the location of the project. Approved plan of the building along with the number of floors. Check if occupancy certificate has been issued by the municipality authority with the approved of Building Plan.
9. Commencement certificate is given by the Municipal Corporation permitting the developer to begin construction.
10. Completion/occupation certificate is given by the concerned authorities to the developer once the said building is complete in all respects and fit for occupation.
11. Stamp Duty & Registration:
12. Registration of an agreement
13. Approved layout plan
14. ownership documents. Check if the land on which the builder is building is his or he has undertaken an agreement with a landlord. If so, check the title of the land ownership with the help of an advocate.
15. Ensure that urban land ceiling NOC (if applicable) has been obtained or not.
16. NOC from water and electricity authorities also have to be obtained.
17. NOC from lift authorities.
18. Has your builder/promoter acquired the approvals from Municipal Corporation, Area Development Authorities, Electricity Boards, Water Supply & Sewerage Boards, Airport Area Authorities?
19. Ensure execution of proper sale agreements on your initial payments.
20. IOD (Intimation of disapproval)
21. Encumbrance certificate

Sunday, April 09, 2006

Purchasing a Flat

Some of the good links regarding the legalities when purchasing a flat.
HDFC
Hitesh
Sify
India infoline
MoneyControl

Saturday, April 08, 2006

Java : Widening, Boxing, Var-args

1. Widening wins over boxing and var-args
2. Boxing wins over var-args
3. Widening of reference variable depends on inheritance(so, Integer cannot be widened to Long. But, Integer widened to Number).
4. Widen and boxing is not possible
5. Boxing and widening is possible
6. var-args can be combined with either boxing or widening

java : order of execution

Following code and output to illustrate the order of execution of consutrctor, initialization blocks

class InitSuper{
InitSuper(int x){System.out.println("super: 1-arg const"); }
InitSuper() { System.out.println("super:no-arg const"); }
static { System.out.println("super:1st static init"); }
{ System.out.println("super:1st instance init"); }
{ System.out.println("super:2nd instance init"); }
static { System.out.println("super:2nd static init"); }
}

class Init extends InitSuper{
Init(int x) { System.out.println("1-arg const"); }
Init() { System.out.println("no-arg const"); }
static { System.out.println("1st static init"); }
{ System.out.println("1st instance init"); }
{ System.out.println("2nd instance init"); }
static { System.out.println("2nd static init"); }
public static void main(String [] args) {
new Init();
new Init(7);
}

Output
super:1st static init
super:2nd static init
1st static init
2nd static init
super:1st instance init
super:2nd instance init
super:no-arg const
1st instance init
2nd instance init
no-arg const
super:1st instance init
super:2nd instance init
super:no-arg const
1st instance init
2nd instance init
1-arg const

Thursday, April 06, 2006

Why is character # not considered to be a part of legal identifer for java compiler?

Why is the identifier e# not a legal identifier for java compiler? The rules for valid identifier given in K&B book are:
----------------------------------------------------------
1. Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!
2. After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
3. In practice, there is no limit to the number of characters an identifier can contain.
4. You can't use a Java keyword as an identifier. Table 1-1 lists all of the Java keywords including one new one for 5.0, enum.
5. Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
----------------------------------------------------------
Accordingly the identifer e# doesn't come in any of the above 5 category.
So, why is it not a legal identifier?

Replies:
1. I guess they forgot to add that any special characters other than the currency symbols are not allowed.

2. The # is not a letter! By letter we should consider A to z, I guess...

Wednesday, March 29, 2006

Problem with applet in IE7

Had problems with loading a applet(that tries to connect using socket) in IE7 using JRE1.5. It used to work in IE6. Was getting the socketPermission error although the java.policy file in the user home had socketPermission for accept, connect, resolve. Then I added the same socketPermission entry in the java.policy file under the security folder of the JRE installed directory. It then worked. Thus, IE7 doesn't check the java.policy file present in the user home. Instead it checks the same present in the JRe installed directory. Bug or enhancement in IE7?

Tuesday, March 28, 2006

Java Tips

Cases when a closing curly brace is followed by semi-colon
  1. anonymous inner class
  2. array initialization using {}

Thursday, March 23, 2006

Difference between Stored Procedure and Function

Stored Procedure :supports deffered name resoultion Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws error
Function wont support deffered name resolution. Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values(SQL Server).Stored Procedure is pre compiled exuction plan where as functions are not.

Wednesday, March 22, 2006

Bug in asList method of class Arrays - Java Tiger: Reply

Not a bug, but I agree it's very surprising. Look at the declaration of asList():

public static <T> List<T> asList(T... a)

"T", like all generic type parameters, has to be a reference type. If you pass an array of reference types, then T becomes the type of that reference, and the individual array elements become the arguments to the function.

But if you pass a primitive array to this function, "T" is assigned the primitive array type itself -- int[], in your example -- and the function sees a single argument of that type. It has to be so, because T can't be assigned to type "int". That "1" is therefore indicating that the function saw the array as a single unit.

Bug in asList method of class Arrays - Java Tiger

asList method of Arrays returns a list. This list corresponding to the primitive array has a odd behaviour. E.g.,

String[] sa = {"one", "two", "three", "four"};
List sList = Arrays.asList(sa);
System.out.println("size of list : " + sList.size());

This prints the size as 4. This is fine. However, the same code for primitive array produces the size as always 1.

int[] ia = {1,2,3};
List iList = Arrays.asList(ia);
System.out.println("size of primitive list : " + iList.size());

This prints the size as 1. Is this a bug?

Friday, March 17, 2006

Making trace files available

There is an undocumented parameter _trace_files_public that if set to true changes the file permissions in the user_dump_dest directory when trace files are created to allow everyone to read them. This parameter can be checked with the following SQL. You can set this parameter by adding the following line to the init.ora file:
# allow trace files to be created with public permissions
_trace_files_public=true
SQL to check the value of this parameter:
SQL> select x.ksppinm name,y.ksppstvl value
from sys.x$ksppi x,sys.x$ksppcv y
where x.inst_id=userenv('Instance')
and y.inst_id=userenv('Instance')
and x.indx=y.indx
and x.ksppinm='_trace_files_public';

Wednesday, March 15, 2006

Who eats my Temp Space

Many a times we get the error : "TEMP SEGMENT MAXIMUM EXTENT EXCEEDED". The following script will provide a list of users and which processes occupy space in the TEMP tablespace.

SET pagesize 10000;
SET linesize 133;
column tablespace format a15 heading 'Tablespace Name';
column segfile# format 9,999 heading 'File|ID';
column spid format 9,999 heading 'Unix|ID';
column segblk# format 999,999,999 heading 'Block|ID';
column size_mb format 999,999,990.00 heading "Mbytes|Used";
column username format a15;
column program format a15;
SELECT
b.tablespace,
b.segfile#,
b.segblk#,
round(((b.blocks*p.value)/1024/1024),2 ) size_mb ,
a.sid,
a.serial#,
a.username,
a.osuser,
a.program,
a.status
FROM v$session a ,
v$sort_usage b ,
v$process c ,
v$parameter p
WHERE p.name='db_block_size'
AND a.saddr = b.session_addr
AND a.paddr=c.addr
ORDER BY b.tablespace,
b.segfile#,
b.segblk#,
b.blocks
/

Thursday, March 09, 2006

Confirmed my understanding

In the earlier blog, the character not being displayed properly by the browser is the browser issue and the code to deal with supplementary character is correct. The link http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=10177 shows the character that will be displayed in browser(which is the one present in xml file when opened by browser). So, to work with supplementary characters, create new String by passing character[] containing the low and high surrogate pairs or the byte[] specifying the encoding. The byte[] can for any code point can be obtained using the link :
Byte for codepoint

Some code to illustrate the unicode support by Character class

public class UnicodeTest{
public static void main(String... args) throws IOException
{
System.out.println("is valid codepoint : " + Character.isValidCodePoint(0x10FFFF));
System.out.println("is valid codepoint : " + Character.isValidCodePoint(0x20FFFF));
int cp = 0x10177;
System.out.println("is valid codepoint : " + Character.isValidCodePoint(cp));
char[] ch = new char[2];
ch = Character.toChars(cp);
int low = ch[0];
int high = ch[1];
System.out.println("Low Surrogate Pair : " + low + " Hexadecimal : " + Integer.toHexString(low) + " Binary String : " + Integer.toBinaryString(low));
System.out.println("High Surrogate Pair : " + high + " Hexadecimal : " + Integer.toHexString(high) + " Binary String : " + Integer.toBinaryString(high));
String st = new String(ch);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("krishna.xml"), "UTF-8"));
out.write("");
out.write("");
out.write(st);
out.write("
");
out.close();

}
}

In the above case, the supplementary character written in xml was not the one it is intended to be. Don't know whether it is the limitation of browser to display the supplementary characters or anything wrong in the way a supplementary character be handled in java code.

Some more understandings on java unicode support

From the start, java had used UTF-16 encoding for encoding the characters. Thus, in the earlier stages when the unicode character set was limited to 16 bits and hence was given full support by java character which was using the utf-16 encoding. Once the unicode was extended to support till the range U+10FFFF, the earlier UTF-16 encoded characters cannot represent characters more than U+FFFF. Hence, in J2se5, support was provided through the Character class. So, the primitive char still supports only the characters till code point: UTF+FFFF. The Java 2 platform uses the UTF-16 representation in char arrays and in the String and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\uD800-\uDBFF), the second from the low-surrogates range (\uDC00-\uDFFF).

A char value, therefore, represents Basic Multilingual Plane (BMP) code points, including the surrogate code points, or code units of the UTF-16 encoding. An int value represents all Unicode code points, including supplementary code points. The lower (least significant) 21 bits of int are used to represent Unicode code points and the upper (most significant) 11 bits must be zero. Unless otherwise specified, the behavior with respect to supplementary characters and surrogate char values is as follows:

* The methods that only accept a char value cannot support supplementary characters. They treat char values from the surrogate ranges as undefined characters. For example, Character.isLetter('\uD840') returns false, even though this specific value if followed by any low-surrogate value in a string would represent a letter.
* The methods that accept an int value support all Unicode characters, including supplementary characters. For example, Character.isLetter(0x2F81A) returns true because the code point value represents a letter (a CJK ideograph).

Back to Unicode support in java

Again got confused in unicode. Some of the terms used are:
1. Coded Character Set
A character Set(collection of characters) where each character has been assigned a unique number. E.g., Unicode character set, where every character is assigned a hexadecimal number.
2. Code Points
The numbers that can be used in a coded character set. Valid code points for Unicode character set is : U+0000 to U+10FFFF (Unicode :4 standard)
3. Supplementary Characters
Characters that could not be represented in the original 16-bit design of Unicode. U+0000 to U+FFFF are referred to as Base Multilingual Plane(BMP) and the others are supplementary characters.
4. Character Encoding Scheme
Mapping from the numbers of one or more coded character sets to sequences of one or more fixed-width code units. e.g., UTF-32, UTF-16, and UTF-8
4. Character Encoding
Mapping from a set of characters to sequences of code units. e.g., UTF-8, ISO-8859-1, GB18030, Shift_JIS.

UTF-16
UTF-16 uses sequences of one or two unsigned 16-bit code units to encode Unicode code points. Values U+0000 to U+FFFF are encoded in one 16-bit unit with the same value. Supplementary characters are encoded in two code units, the first from the high-surrogates range (U+D800 to U+DBFF), the second from the low-surrogates range (U+DC00 to U+DFFF). This may seem similar in concept to multi-byte encodings, but there is an important difference: The values U+D800 to U+DFFF are reserved for use in UTF-16; no characters are assigned to them as code points. This means, software can tell for each individual code unit in a string whether it represents a one-unit character or whether it is the first or second unit of a two-unit character. This is a significant improvement over some traditional multi-byte character encodings, where the byte value 0x41 could mean the letter "A" or be the second byte of a two-byte character.


Monday, March 06, 2006

Least Integer to lose precision when converted to Floating point

The first integer at which assigning to float and casting back to int loses precision is : 16777217. The following code when run, gives the output as:

class Q44
{
public static void main(String[] args)
{
int i=0, y;
float j=0;
while(true)
{
j = i;
y=(int)j;
if( (y-i) != 0)
{
System.out.println("i = " + i);
break;
}
i++;
}
i = -1;
while(true)
{
j = i;
y=(int)j;
if( (y-i) != 0)
{
System.out.println("i = " + i);
break;
}
i--;
}


}
}


i = 16777217
i = -16777217

Floating points are first converted to form : N = ± (1.b1b2b3b4 ...)2 x 2+E
The left most one is not stored(always 1). The bits b1b2b3 etc.,(upto 23 bits) is what goes into the mantissa part. Hence, the first maximum bit for an integer can be 24 successive one's. (23 One's for mantissa and one implicit 1). 24 successive one corresponds to the number : 16777215. The next number is 16777216 for which the bit pattern is : 1000000000000000000000000
ie., one followed by 24 zero. So, even though the 24th zero is not stored, precision is not lost. Because when we convert back it is restored. So, the maximum integer without losing precision that can be converted back from float is now : 16777216

Now, if we consider the next number (16777217) for which the bit pattern is : 1000000000000000000000001. This has 1 followed by 23 zeros and then a 1. Because of 1 in the 24th bit, the 23rd bit will be rounded to 1 and the first precision loss comes for this number. Thus, the number 16777217 is the first integer number which when converted to float and converted back to integer will lose the precision as proved by the output of the above code.

Wednesday, March 01, 2006

.Net Framework

Was feeling lazy to work today. Hence, looked at .net framework programming......Some highlights of points learnt for future reference
1. .Net currently supports around 20 languages to be compiled into IL(Intermediate Language) format.
2. For shift from J2EE to dot net, c# can be a better option.
3. A simple helloworld C# code is:
class App{
public static void Main(){
System.Console.WriteLine("Hello World!");
}
}
4. To compile the above code, type "csc filename.cs". This generates the filename.exe. (for vb, use vbc and for javascript, jsc)
5. Hierarchy : Managed Executable -> CLR(JIT compilation) -> OS
6. CLR is similar to the other execution engine like JVM for J2EE. The CLR supplies memory management, type safety, code verifiability, thread management and security.
7. Important points are
  • Managed Code is never interpreted

  • Managed code doesn't run in virtual machine.

8. CIL(Common IL) is the high level assembly language includes instructions for advanced programming concepts as instantiating objects or calling virtual functions.
9. The CLR translates these and every other IL instruction into a native machine language instruction at runtime, and then executes the code natively.
10. Metadata describes class definitions, method signatures, parameter types and return values.
11. The exe generated out of compiling the managed code contains the metadata and the IL. We can use the IL disassemebler(ILDASM) to view the structure of the managed exe.
12. At runtime, this exe is JIT compiled by the CLR and converted into the machine language instructions.
13. Some of the benchmarck results shows dot net executed code is 2-3 times faster than the J2EE...

JIT COMPILATION
The first time that a managed executable references a class or type (such as a structure, interface, enumerated type or primitive type) the system must load the code module or managed module that implements the type. At the point of loading, the JIT compiler creates method stubs in native machine language for every member method in the newly loaded class. These stubs include nothing but a jump into a special function in the JIT compiler.

Once the stub functions are created, the system fixes up any method calls in the referencing code to point to the new stub functions. At this time no JIT compilation of the type's code has occurred. However, if a managed application references a managed type, it is likely to call methods on this type (in fact it is almost inevitable).

When one of the stub functions is called the stub causes execution to jump into the JIT compiler. The JIT compiler looks up the source code (IL and metadata) in the associated managed module, and builds native machine code for the function on the fly. Then, it replaces the stub function with a jump to the newly JIT compiled function. The next time this same method is called in source code, it will be executed full speed without any need for compilation or extra steps.

The good thing about this approach is that the system never wastes time JIT compiling methods that won't be called by this run of your application.

Friday, February 03, 2006

ADF active data model

This link explains how a change to model is automatically notified to client in case of ADFBC, so that there is no need to transfer the data back and forth.