Thursday, March 01, 2007

Sun Updates Mobile Java Platform

Sun Microsystems announced the availability of the Mobile Services Architecture (MSA), the next generation Java platform for mobile phones and other handheld devices. MSA is available now for mobile devices and Sun's NetBeans development platform.

Sun developed the MSA along with 13 other companies, including operators, OEMs and software vendors. The MSA is the next step in the evolution of Sun's mobile API set, Java Technology for the Wireless Industry (JTWI).

"What we did with JTWI was make a compilation of a number of specs together to create a standard platform developer could count on being in handsets. MSA is the next generation. It supersedes JTWI with much more features and functionality than what we had," John Muhlner, group manager for Java ME product marketing at Sun (Quote), told internetnews.com at an event to announce the new platform.


The new APIs (define) in MSA allow for the creation of mobile applications and services that use 3D graphics, personal information management, Bluetooth, animation, Web services, location services and payment services.

MSA also adds a Wireless Client optimized to support multiple, concurrent wireless applications, the Device Test Suite 2.0 for testing the quality and compliance of APIs to the specs, and the NetBeans Mobility Pack 5.5 for building applications in the NetBeans environment.


Finally, there is the Java Wireless Toolkit 2.5 for Connected Limited Device Configuration (CLDC), a collection of tools for building applications and a wireless platform emulator for testing the applications.

Java ME was severely fragmented for the longest time, and MSA will bring it some unity, said Muhlner. "These platform specs take the specific technologies and clarify or define certain options within the spec. It reduces fragmentation and makes for a more consistent application environment."


Jeff Griffin, MSA Expert Group representative for cell phone maker Sony Ericsson, agreed. "MSA is critical for us in the next phase of making Java more usable in mobile phones. The technology continues to grow, new JSRs are added to the mix. This means imp fragmentation. What umbrella JSRs like this are good is setting a baseline and saying everyone needs to start here," he said.

Thursday, January 18, 2007

SCJP 5.0 Mock Exams - Generics


SCJP 5.0 Mock Exams - Generics


  1. what is the result compiling and running the following piece of code?

import java.util.*;

class Test {

public static void main(String [] args) {

Set vals = new TreeSet<String>();

vals.add("one");

vals.add(1);

vals.add("two");

System.out.println(vals);

}

}


Options :

  1. Does not Compile

  2. Compiles with warning and prints output [one, 1, two]

  3. Compiles without warning and prints output [one, 1, two]

  4. Compiles with warning and throws exception at runtime

  5. Compiles without warning and throws exception at runtime


Answer :

D are correct Answers.

Compiles with warning due to un-safe assignment List vals = new ArrayList<String>();

Since TreeSet<String> is used, it will try to sort by natural order. Due to the presence of Integer (vals.add(1);) in the collection, it will throw ClassCastException at runtime(While try to cast Integer in to String).


  1. which of the following piece of code can be inserted to make the following code to compile?

import java.util.*;

class PickThePiece {

public static void main(String [] args) {

//insert the first line here

datas.add("delhi")

datas.add(new Object());

//insert the second line here

}

}

Options :

  1. List<Object> datas = new LinkedList<Object>();

String data = datas.get(0);

  1. List<Object> datas = new LinkedList<Object>();

String data = (String)datas.get(0);

  1. List<String> datas = new LinkedList<String>();

String data = (String)datas.get(0);

  1. List<String> datas = new LinkedList<String>();

String data = datas.get(0);

  1. all the above


Answer :

B,C, and D are the correct answers.

A is wrong because datas.get(0) will return a Object which cannot be directly assigned to a String without casting.


  1. What is the result of compiling and running the following code?

import java.util.*;

class SampleTest {

public static void main(String [] args) {

List samples = new ArrayList();

samples.add("100");

samples.add(200);

samples.add("300");

printData(samples);

}


static void printData(List<String> samples) {

for(String sample : samples) {

System.out.print(sample + “ “);

}

}

}


Options :


  1. Prints 100 200 300

  2. Compile time error

  3. Compiles without warning

  4. Compiles with warning

  5. Runtime Exception


Answer :

D, E are correct answers.

D) It produces warning since un-safe List samples is passed to a type safe collections(as a method argument).

E) Since samples.add(200), adds a Integer in to collection. While iterating through enhanced for loop, Integer is tried to cast to String causes ClassCastException.


  1. Consider the following code, select the valid options given below.

class Fruit {}

class Apple extends Fruit {}

class Orange extends Fruit {}


Options :

  1. List<? extends Fruit> stmt = new ArrayList<Fruit>();

  2. List<? super Apple> stmt = new ArrayList<Fruit>();

  3. List<? extends Fruit> stmt = new ArrayList<Apple>();

  4. List<? super Orange> stmt = new ArrayList<Orange>();

  5. All the above

  6. None of these


Answer :

E is the correct answer. All these options are valid.

Keyword “super “ – allows the type followed by keyword and its super type(parent ).

Keyword “extends” – allows the type followed by keyword and its sub type(child).


  1. What is the output of the following code?

import java.util.*;

class Color {}

class Blue extends Color {}

class Red extends Color {}


class TestColor {

public static void main(String [] args) {

1) List<Color> colors = new ArrayList<Color>();

2) colors.add(new Color());

3) colors.add(new Blue());

4) colors.add(new Red());

5) List<Color> newClr = alterColor(colors);

6) System.out.println(newClr);

}


static void alterColor(List clrs) {

7) clrs.add(new Object());

}

}


Options :

  1. Compile time error due to lines 3 and 4.

  2. Compile time error due to line 5.

  3. Compile time error due to line 7.

  4. Compiles with warning and produces some output.

  5. Compiles without warning and produces some output.

  6. Compiles fine and Exception is thrown at runtime.


Answers :

D is the correct answer.

Warning is due to non-type safe method call. Within the alterColor() method adding a new Object is not a issue because the collection becomes non-type safe.


  1. what is the result of the following code ?

import java.util.*;


class Bird {}

class Duck extends Bird {}

class Hen extends Bird {}


class FuzzyTest {

public static void main(String [] args) {

Map<String, Bird> birds = new HashMap<String, Bird>();

birds.put("bird", new Bird());

birds.put("hen", new Hen());

birds.put("duck", new Duck());

Map bs = addBirds(birds);

for(String b : bs.keySet())

System.out.print(b + " ");

}

static Map addBirds(Map brds) {

brds.put("bird", new Object());

return brds;

}

}


Options :

  1. Compiles and prints output “bird hen duck”.

  2. Compiles and prints output “bird duck hen”.

  3. Compiles and prints some output order cannot be determined.

  4. Run time Exception.

  5. Compilation fails.


Answer :

E is the correct answer.

Since bs is non-typesafe collection, bs.keySet() returns Object. But in enhanced for loop string is used to catch the returned values, that leads to compilation error.


  1. what are the valid statements can be filled in the blank, to make the code to compile and run?

import java.util.*;

interface Eat{}

class Animal implements Eat{}

class Dog extends Animal {}

class Cat extends Animal {}


class AnimalTest {

public static void main(String[] args) {

List<Animal> a = new ArrayList<Animal>();

List<Dog> d = new ArrayList<Dog>();

List<Cat> c = new ArrayList<Cat>();

checkAnimal(a);

checkAnimal(d);

checkAnimal(c);

}

static void checkAnimal( ________________ pets) {

System.out.print(“animals checked here”);

}

}


Options :

  1. List<? extends Animal>

  2. List<? super Animal>

  3. List<? extends Eat>

  4. List<? super Eat>

  5. List<?>

  6. All of the above


Answer :

A , C and E are the correct answers.

Keyword “super “ – allows the type followed by keyword and its super type(parent ).

Keyword “extends” – allows the type followed by keyword and its sub type(child).

Wild card ? – allows everything.


  1. what is the output of the following code?

import java.util.*;

class Example {

public static void main(String [] args) {

Set<String> values = new TreeSet<String>();

values.add(“yet”);

values.add(“get”);

values.add(“bet”);

displayValues(values);

}

static void displayValues(Set<?> values) {

values.add(“wet”)

for(Object v : values) ;

System.out.print(v + “ “);

}

}


Options :

  1. Compiles and gives output “yet get bet wet”.

  2. Compiles and gives output “bet get wet yet”.

  3. Compilation fails

  4. Compiles with warning and Exception thrown at runtime.

  5. Compiles without warning and Exception thrown at runtime.


Answer :

C is the correct answer.

When we use wildcard(?) to catch the collection , then modifications are not allowed in that collection. Here values.add(“wet”) will throw error at compilation time.


  1. Choose the valid ways to create an object for the following class.

class GenTest<T super Number> {

T num;

public T checkNumber(T n) {

return n;

}

}


Options :

  1. Compilation fails.

  2. GenTest<Number> gt = new GenTest<Number>();


  1. GenTest<Integer> gt = new GenTest<Integer>();


  1. GenTest<Object> gt = new GenTest<Object>();


  1. None of the above.



Answer :

A is the correct answer.

Since <T super Number> is an invalid syntax. If super keyword is replaced by extends, then B and C will be the valid answers.


  1. Choose the valid constructors for the following class.

class Generics<T>{}


Options :

  1. public Generics(){}

  2. public Generics<T>(){}

  3. public <T> Generics(T t){}

  4. public <T> Generics(){}

  5. All the above.


Answer :

A,C and D are correct answers.

B is incorrect because of improper syntax.













Servlets Interview Questions

Servlet Interview Questions

1. What is the servlet?
Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently

2. What is the architechture of servlet package?
Servlet Interface is the central abstraction. All servlets implements this Servlet 
Interface either direclty or indirectly
( may implement or extend Servlet Interfaces sub classes or sub interfaces)


Servlet
|
Generic Servlet
|
HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
|
MyServlet

3. What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.

4. What's the difference between servlets and applets?
Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.

5. What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

6. When doGET() method will going to execute?
When we specified method='GET' in HTML
Example : < form name='SSS' method='GET'>

7. When doPOST() method will going to execute?
When we specified method='POST' in HTML
< form name='SSS' method='POST' >

8. What is the difference between Difference between doGet() and doPost()?
GET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).

POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info
on the browser.

9. What is the servlet life cycle?
When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method

Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.

10. Which protocol will be used by browser and servlet to communicate ?
HTTP




Source : www.javabeat.net











Servlets Interview Questions

Servlet Interview Questions


11. In how many ways we can track the sessions?
Method 1) By URL rewriting

Method 2) Using Session object

Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);

Get a Value from the session
session.getValue(session.getId());

Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);


At the end of the session, we can inactivate the session by using the following command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields


12. How Can You invoke other web resources (or other servelt / jsp ) ?
Servelt can invoke other Web resources in two ways: indirect and direct.

Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)

Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.

You can get this object using getRequestDispatcher("URL") method. You can get this object from either a request or a Context.

Example :
RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}

13. How Can you include other Resources in the Response?
Using include method of a RequestDispatcher object.

Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.

Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");
&nbspif (dispatcher != null)
&nbspdispatcher.include(request, response);
}

14. What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?
The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

15. What is the use of ServletContext ?
Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.

16. Is there any way to generate PDF'S dynamically in servlets?
We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.

17. What is the difference between using getSession(true) and getSession(false) methods?
getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.

getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

Source : www.javabeat.net

Struts Interview Questions

Struts Interview Questions

Question21: What are the disadvantages of Struts?
Answer: Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.

b) Harder to learn
Struts are harder to learn, benchmark and optimize.

Question22: What is Struts Flow?
Answer: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html )

Question23: What are the difference between <bean:message> and <bean:write>?
Answer: <bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.

<bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data.

Question24: What is LookupDispatchAction?
Answer: An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. (Ref. http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html).

Question25: What are the components of Struts?
Answer: Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.
Model: Components like business logic / business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.


Question26: What are Tag Libraries provided with Struts?
Answer: Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are:
a) Bean Tags: Bean Tags are used to access the beans and their properties.
b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc..
c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets.
d) Nested Tags: Nested Tags helps to work with the nested context.

Question27: What are the core classes of the Struts Framework?
Answer:
Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.

Question28: What are difference between ActionErrors and ActionMessage?
Answer: ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.
Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message.

ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form).

Question29: How you will handle exceptions in Struts?
Answer: In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:

<exception

key="database.error.duplicate"

path="/UserExists.jsp"

type="mybank.account.DuplicateUserException"/>

b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.


Question30: What do you understand by JSP Actions?
Answer: JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:

<jsp:include/>

<jsp:forward/>

<jsp:plugin/>

<jsp:usebean/>

<jsp:setProperty/>

<jsp:getProperty/>


Source : www.javabeat.net

Struts Interview Questions

Struts Interview Questions

Question11: Why cant we overide create method in StatelessSessionBean?
Answer:
From the EJB Spec : - A Session bean's home interface defines one or morecreate(...) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean's remote interface type. The home interface of a stateless session bean must have one create method that takes no arguments.

Question12: Is struts threadsafe?Give an example?
Answer:
Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.

Question13: Can we Serialize static variable?
Answer:
Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular object's state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields. There are four basic things you must do when you are making a class serializable. They are:

  1. Implement the Serializable interface.
  2. Make sure that instance-level, locally defined state is serialized properly.
  3. Make sure that superclass state is serialized properly.
  4. Override equals( )and hashCode( ).
    it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process .... (Source: http://www.oreilly.com/catalog/javarmi/chapter/ch10.html)
Question14: What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
Answer:
tiles-def.xml is is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View. See more at http://www.roseindia.net/struts/using-tiles-defs-xml.shtml.

The
resourcebundle.properties file is used to configure the message (error/ other messages) for the struts applications.

The file validation.xml is used to declare sets of validations that should be applied to Form Beans. Fpr more information please visit http://www.roseindia.net/struts/address_struts_validator.shtml.

Question15: What is the difference between perform() and execute() methods?
Answer:
Perform method is the method which was deprecated in the Struts Version 1.1.
In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.

Question16: What are the various Struts tag libraries?
Answer:
Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application


Question17: What do you understand by DispatchAction?
Answer:
DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class.
For example:
A package might include separate RegCreate, RegSave, and RegDelete Actions, which just perform different operations on the same RegBean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action.

A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.

<html:hidden property="dispatch" value="error"/>
<SCRIPT>function set(target) {document.forms[0].dispatch.value=target;}</SCRIPT>
<html:submit onclick="set('save');">SAVE</html:submit>
<html:submit onclick="set('create');">SAVE AS NEW</html:submitl>
<html:submit onclick="set('delete);">DELETE</html:submit>

Then, in the Action you can setup different methods to handle the different operations, and branch to one or the other depending on which value is passed in the dispatch field.

String dispatch = myForm.getDispatch();
if ("create".equals(dispatch)) { ...
if ("save".equals(dispatch)) { ...

The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing, but without messy branching logic. The base perform method will check a dispatch field for you, and invoke the indicated method. The only catch is that the dispatch methods must use the same signature as perform. This is a very modest requirement, since in practice you usually end up doing that anyway.

To convert an Action that was switching on a dispatch field to a DispatchAction, you simply need to create methods like this

public ActionForward create(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

public ActionForward save(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. So a mapping for our example might look like this:

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="dispatch"/>

If you wanted to use the property "o" instead, as in o=create, you would change the mapping to

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="o"/>

Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each?

You can, but the value of the button is also its label. This means if the page designers want to label the button something different, they have to coordinate the Action programmer. Localization becomes virtually impossible. (Source: http://husted.com/struts/tips/002.html).

Question18: How Struts relates to J2EE?
Answer:
Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.

Question19: What is Struts actions and action mappings?
Answer:
A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward.

An action can perform tasks such as validating a user name and password.

An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action.

An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.

Question20: Can I setup Apache Struts to use multiple configuration files?
Answer: Yes Struts can use multiple configuration files. Here is the configuration example:
<servlet>
<servlet-name>banking</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml,
/WEB-INF/struts-authentication.xml,
/WEB-INF/struts-help.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Source : www.javabeat.net

Struts Interview Questions

Struts Interview Questions

Q1: What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

Q2: How you will make available any Message Resources Definitions file to the Struts Framework Environment?
A:
Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter="MessageResources" />

Q3: What is Action Class?
A:
The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Q4: Write code of any Action Class?
A:
Here is the code of Action Class that returns the ActionForward object.
TestAction.java
package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

Q5: What is ActionForm?
A:
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

Q6: What is Struts Validator Framework?
A:
Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

Q7. Give the Details of XML files used in Validator Framework?
A:
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Q8. How you will display validation fail errors on jsp page?
A:
Following tag displays all the errors:
<html:errors/>

Q9. How you will enable front-end validation based on the xml in validation.xml?
A:
The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

Question10: What is RequestProcessor and RequestDispatcher?
Answer:
The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.

The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like
The ActionServlet Class
The RequestProcessor Class
The Action Class


The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application.
The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>



All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below.
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
<url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name
The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.

Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method.
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception;

The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn’t already exist. The strut framework will create only a single instance of each Action class in your application.

Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>

Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>

The action forward mappings also can be specified in a global section, independent of any specific action mapping.
<global-forwards>
<forward name="Success" path="/action/somejsp.jsp" />
<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>


public interface RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

getRequestDispatcher

public RequestDispatcher getRequestDispatcher(java.lang.String path)

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.
The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.

Parameters:
path - a String specifying the pathname to the resource
Returns:
a RequestDispatcher object that acts as a wrapper for the resource at the specified path
See Also:
RequestDispatcher, getContext(java.lang.String)


getNamedDispatcher

public RequestDispatcher getNamedDispatcher(java.lang.String name)

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. A servlet instance can determine its name using ServletConfig.getServletName().
This method returns null if the ServletContext cannot return a RequestDispatcher for any reason.

Parameters:
name - a String specifying the name of a servlet to wrap
Returns:
a RequestDispatcher object that acts as a wrapper for the named servlet
See Also:
RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName()

Source : www.javabeat.net

JDBC Interview Questions - FAQs


JDBC - Frequently Asked Questions or Interview Questions(FAQs)

1. What is JDBC?

JDBC technology is an API that lets you access virtually any tabular data source from the Java programming language. It provides cross-DBMS connectivity to a wide range of SQL databases, and now, with the new JDBC API, it also provides access to other tabular data sources, such as spreadsheets or flat files.

2. What's the JDBC 3.0 API?

The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including scrollable result sets and the SQL:1999 data types.



3. Does the JDBC-ODBC Bridge support the new features in the JDBC 3.0 API?


The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.



4. Can the JDBC-ODBC Bridge be used with applets?


Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.

Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.



5. How do I start debugging problems related to the JDBC API?


A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations.

If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)


6. How can I use the JDBC API to access a desktop database like Microsoft Access over the network?


Most desktop databases currently require a JDBC solution that uses ODBC underneath. This is because the vendors of these database products haven't implemented all-Java JDBC drivers.

The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of available JDBC drivers.

The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge, however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is free.



7. Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?


Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in functionality between ODBC drivers, the functionality of the bridge may be affected. The bridge works with popular PC databases, such as Microsoft Access and FoxPro.



8. What causes the "No suitable driver" error?


"No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are specifying is not being recognized by your JDBC driver.

In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your configuration to be sure that the shared libraries are accessible to the Bridge.



9. Why isn't the java.sql.DriverManager class being found?


This problem can be caused by running a JDBC applet in a browser that supports the JDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBC API, so the DriverManager class typically isn't found by the Java virtual machine running in the browser.

Here's a solution that doesn't require any additional configuration of your web clients. Remember that classes in the java.* packages cannot be downloaded by most browsers for security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of the java.sql.* classes that have been renamed to jdbc.sql.*, along with a version of their driver that uses these modified classes. If you import jdbc.sql.* in your applet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your applet's codebase, then all of the JDBC classes needed by the applet can be downloaded by the browser at run time, including the DriverManager class.

This solution will allow your applet to work in any client browser that supports the JDK 1.0.2. Your applet will also work in browsers that support the JDK 1.1, although you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution outlined here is just an example and that other solutions are possible.



10. How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX method for each column?


The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the cost of a function call in any scenario. We welcome input from developers on this issue.



11. Why does the ODBC driver manager return 'Data source name not found and no default driver specified Vendor: 0'


This type of error occurs during an attempt to connect to a database with the bridge. First, note that the error is coming from the ODBC driver manager. This indicates that the bridge-which is a normal ODBC client-has successfully called ODBC, so the problem isn't due to native libraries not being present. In this case, it appears that the error is due to the fact that an ODBC DSN (data source name) needs to be configured on the client machine. Developers often forget to do this, thinking that the bridge will magically find the DSN they configured on their remote server machine.



12. Are all the required JDBC drivers to establish connectivity to my database part of the JDK?


No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are considering bundling JDBC technology- enabled drivers in the future.



13. Is the JDBC-ODBC Bridge multi-threaded?


No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.



14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?


No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.



15. Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next works?

You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.



16. How can I retrieve a String or other object type without creating a new object each time?


Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object.

We are studying this issue to see if it is an area in which the JDBC API should be improved. Stay tuned, and please send us any comments you have on this question.



17. There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of rows in a result set?


No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.



18. I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, Standard Edition (formerly JDK 1.2). I'm a beginner with the JDBC API, and I would like to start with the Bridge. How do I do it?


The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.



19. If I use the JDBC API, do I have to use ODBC underneath?


No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.



20. Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a database?


You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.



21. What are the different types of JDBC drivers?


JDBC technology drivers fit into one of four categories:

  1. A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBC-ODBC Bridge Driver.

  2. A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
  3. A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
  4. A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

22. Are there recommended programming practices for using JDBC connections?

The general rule is to get the connection from the connection pool as late as possible and give it back to the connection pool as soon as possible. Ensure that the connection is a method variable, and get and release the connection within the same method as where you use it (each thread should have its own connection). The cost of getting the connection is small, the prepared statement cache will reduce the preparation time, the set statements are small, the execute needs to be done no matter what the usage, and the close is small. It is not recommended to

create the connection at ejbCreate/activate and close it on ejbRemove/pasivate.



23. Why should I not use DriverManager.getConnection?


DriverManager.getConnection can cause a deadlock. In the server, all DriverManager calls are class-synchronized including many frequent calls that all drivers make, and JDBC drivers do a lot of synchronization internally. One long-waiting call can stop all JDBC work in the whole JVM and cause deadlocks. Also, you should not reregister the driver repeatedly. Regardless of the DBMS state, the one driver that is initially loaded at startup will always work.



24. Can I use a prepared statement across multiple transactions?


Yes. Every transaction uses a dedicated JDBC connection, and all database interaction needs to use this connection object in order to participate in the transaction. So a prepared statement is tied to a particular connection and can't be shared with other connections. But a prepared statement can span transactions.


25. Why do I get a java.lang.AbstractMethodError when calling a method on a driver?


This usually indicates that the driver has not implemented the method. For instance, you might be calling a JDBC 3.0 method on a driver that has only implemented the JDBC 2.0 methods.


26. Why do I get "ResourceException: No Resource Available"?


One common reason is that you have too many consumers (connection users) for the number of configured JDBC connections in the connection pool or execute threads on the server.

Another reason may be that the refresh testing process has reserved one or more connections for testing so these connections are briefly unavailable.


27. How do I ensure that a new database connection is created each time an EJB's container-managed transaction is started (so that I get a new authentication/authorization each time)?


The EJB should be tx-requires, which means it will start a transaction when called if one is not underway already, or will join the transaction in progress if there is one. Your code will use the standard JTS/JTA API to obtain and start a UserTransaction. Then you should obtain your JDBC connection from a tx data source, and it will be included in the transaction. To get a new connection each time, you could use the dynamic pool API to make a one-connection pool. We suggest configuring the server to have a one-connection pool and a tx data source for it at startup. Then when you want to do a transaction in an external client, you would destroy the initial pool and recreate it with the DBMS user you want. This will allow you to use the tx data source to get a connection, which if obtained in the context of a running UserTransaction, will get automatically included in the tx.


28. If it is a WebLogic DataSource, then you get a stub for the Connection instance, not a connection pool in the local process.

If a distributed transaction involves JMS and JDBC, how do I ensure that the JDBC update is available when the JMS message is processed?

The problem is that an application can receive the JMS message from the destination before the associated JDBC data is in the database.

Distributed transactions guarantee all involved changes will either succeed or fail as a unit, but cannot guarantee that they will happen exactly simultaneously (the transaction manager instructs all resource managers to commit but cannot control the timing of the completion of that operation).

For the WebLogic transaction manager, if the JDBC connection pool and the JMS server are both on the same server, and the transaction starts on the same server, the changes are committed in the order in which they were asked for by the transaction. This is not supported behavior, it just happens to be the current behavior. So if you can co-locate JMS and the JDBC connection pool, then you may have a chance.

You could send the JMS message with a delayed birth-time, and hope that this is good enough.

If the receiver fails to find the associated JDBC record, it could rollback/recover the message. You could use the WebLogic JMS redelivery delay feature to prevent the message from being redelivered instantly.


29. If an application calls DataSource.getConnection multiple times in the same thread and transaction, will WebLogic Server handle giving me the same connection and transaction?


A common scenario might be to have multiple methods that are called within a transaction (begin/commit) that do something like the following:

Context ctx = new InitialContext();
DataSource ds = (javax.sql.DataSource) ctx.lookup("connpoll");
// work using Connection

In this case, all of the work will be done within the transaction and the same underlying JDBC connection will be used as long as the DataSource ds is a tx data source.



30. Why do I get a SystemException failure when trying to enlist my XAResource in a client?


WebLogic Server does not allow you to register or enlist an XA resource on a client. The reason for this restriction is that a client is deemed to be less reliable than a server in terms of availability. This is also why a client is not allowed to act as a transaction coordinator and register Synchronization objects.

Your client could invoke a remote object on a server that accesses the resource within a transaction. If it's a JDBC resource, then you can configure a JDBCConnectionPool and JDBCTxDataSource using an Oracle XA driver (Oracle thin or WebLogic Type 4 driver for Oracle) and obtain a connection from the data source. Or the client could look up the data source using JNDI and retrieve and manipulate a connection in a transaction. Transaction enlistment is performed automatically.



31. What causes an OCIW32.dll error?


You may see the following error message when using your JDBC driver for Oracle: "The ordinal 40 could not be loaded in the dynamic link library OCIW32.dll." This problem is caused by an out-of-date version of OCIW32.DLL in your system directory. Some programs install this file in the system directory in order to run. If you remove this file from the system directory you should no longer receive this error.



32. What type of object is returned by ResultSet.getObject() when using the WebLogic jDriver for Oracle?


WebLogic jDriver for Oracle always returns a Java object that preserves the precision of the data retrieved. It returns the following from the getObject() method:

  • For columns of types NUMBER(n) and NUMBER(m,n): a Double is returned if the defined precision of the column can be represented by a Double; otherwise BigDecimal is returned.
  • For columns of type NUMBER: Because there is no explicit precision, the Java type to return is determined based on the actual value in each row, and this may vary from row to row. An Integer is returned if the value has a zero-valued fractional component and the value can be represented by an integer.

For example, 1.0000 will be an integer. A long is returned for a value such as 123456789123.00000. If a value has a non-zero fractional component, a Double is returned if the precision of the value can be represented by a Double; otherwise a BigDecimal is returned.



33. How do I call Oracle stored procedures that take no parameters?


Try this:

  CallableStatement cstmt = conn.prepareCall("Begin procName;
END;");
cstmt.execute();

where procName is the name of an Oracle stored procedure. This is standard Oracle SQL syntax that works with any Oracle DBMS. You can also use the following syntax:

 CallableStatement cstmt = conn.prepareCall("{call procName};");
cstmt.execute();

This code, which conforms to the Java Extended SQL specification, will work with any DBMS, not just Oracle.



34. How do I bind string values in a PreparedStatement?


Suppose you are trying to get the PreparedStatement class to bind Strings in a statement. The setString() method doesn't seem to work. Here is how you have set up the PreparedStatement:

  String pstmt = "select n_name from n_table where n_name LIKE '?%'";
PreparedStatement ps = conn.prepareStatement(pstmt);
ps.setString(1, "SMIT");
ResultSet rs = ps.executeQuery();

The preceding code does not work because the complete value needs to be specified in a String (without using embedded quotes) and then bound to an unquoted question mark (?). Here is the corrected code:

  String matchvalue = "smit%";
String pstmt = "select n_name from n_table where n_name LIKE ?";
PreparedStatement ps = conn.prepareStatement(pstmt);
  ps.setString(1, matchvalue);
ResultSet rs = ps.executeQuery();

35. Why do I get unexpected characters from 8-bit character sets in WebLogic jDriver for Oracle?


If you are using an Oracle database with an 8-bit character set on Solaris, make sure you set NLS_LANG to the proper value on the client. If NLS_LANG is not set, it defaults to a 7-bit ASCII character set, and tries to map characters greater than ASCII 128 to a reasonable approximation (for example, &aacute;, &agrave;, &acirc; would all map to a). Other characters are mapped to a question mark (?).


36. How do I learn what codesets are available in Oracle?


To find out what codesets you currently have available in Oracle, execute the following SQL query from SQLPlus at the command line:

 SQL> SELECT value FROM v$nls_valid_values
WHERE parameter='CHARACTERSET';

The response lists all codesets currently installed on your system. This listing will look something like the following shortened list:

  VALUE
-----------------------------------------------------------
US7ASCII
WE8DEC
WE8HP
US8PC437
WE8EBCDIC37
WE8EBCDIC500
WE8EBCDIC285
...

If you want to constrain the value in the query to a specific codeset you are searching for, you can use a SQL query like the following:

 SQL> SELECT value FROM v$nls_valid_values 
WHERE parameter='CHARACTERSET' and VALUE='AL24UTFFSS';

This would produce the following response if the codeset is installed:

  VALUE
-------------------------------------------------------------
AL24UTFFSS

You can use Oracle's installation tools to install additional codesets. Contact Oracle for more information.



37. How do I look up an "ORA" SQLException?


If your WebLogic jDriver for Oracle application produces an SQLException, you can look up the Oracle error by using the oerr command. For example, if you see the following SQLException:

  java.sql.SQLException: ORA-12536: TNS: operation would block

You can find the description of error ORA-12536 can be found with the command:

  > oerr ora 12536
38. What is error "ORA-6502?"


The default length of a string bound to an OUTPUT parameter of a CallableStatement is 128 characters. If the value you assign to the bound parameter exceeds that length, you will get this error.

You can adjust the length of the value of the bound parameter by passing an explicit length with the scale argument to the CallableStatement.registerOutputParameter() method.


39. Why do I get an error while trying to retrieve the text for ORA-12705?


This error occurs when you have not set the ORACLE_HOME environment variable properly. In order to use WebLogic jDriver for Oracle, the Oracle client software needs to be installed and ORACLE_HOME must be set.

You may also see this error message if you try to use WebLogic jDriver for Oracle's internationalization capabilities with a language/codeset combination that is not installed on your system. If you get the ORA-12705 error with the correct error text, then either you have set NLS_LANG improperly, or you do not have the right codesets installed on your system.



40. Why do I run out of resources during updates with Oracle's database link?


When you use Oracle's database link to update your database, you may get error "maximum number of temporary table locks exceeded" even if you close your result sets and statements when you finish.

The database link is an object in the local database that allows you to access tables, views, and so forth in a remote database. The database link is controlled by the Oracle server, so the driver has no control over its use of resources. The link appears to perform the commit (since other processes could see the records that were being created), but it doesn't free any resources until the connection is closed. The solution is to remove the database link and use the JDBC driver to do your selects, inserts, and updates.



41. Why does executing the PreparedStatement class cause a "TRUNC fails: ORA-00932: inconsistent datatypes" error?


According to Oracle Metalink Bug Database Doc ID: 144784.1, in the absence of explicit data typecasting, OCI assumes that a bind variable is a CHAR data type. If the SQL statement intends to use the bind variable as a DATE data type, but OCI thought it was a CHAR, the SQL parser will have a conflict in data types. The fix is to explicitly use data conversion functions to convert the bind variables in the problem queries. For example, a select string of

String st = "select count(*) from simple_table where TRUNC(mydate) = TRUNC(?)"; 

should be changed to:

String st = "select count(*) from simple_table where TRUNC(mydate) = TRUNC(TO_DATE(?))";
42. How do I create and update Oracle Blob fields?


The following code sample shows how to create and update Oracle Blob fields.

public void insert() throws SQLException {
try {
    // Connect to the database using WebLogic JDBC connection pool
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
InitialContext ctx = new InitialContext(ht);
javax.sql.DataSource ds = (javax.sql.DataSource)
ctx.lookup("java:comp/env/jdbc/DSName");
Connection conn = ds.getConnection();
    // This is necessary in any case where you are doing
// a select for update. Not doing this will result in a ORA-1002
conn.setAutoCommit (false);
    BLOB blob = null;
    // Create a Statement
Statement stmt = conn.createStatement ();
    // Drop the table if it exists
try {
stmt.execute ("drop table ImageTable");
System.out.println("Table droped ...");
}
catch (SQLException e) {
System.out.println("Table does not exist");
}
    // Create the table
stmt.execute ("create table ImageTable (column1 varchar2(20),
image BLOB)");
System.out.println("Table created ...");
    // create a blob entry in the table
stmt.execute("insert into ImageTable values ('one', empty_blob())");
stmt.execute("commit");
System.out.println("inserted empty blob");
String cmd = "select * from ImageTable for update";
ResultSet rset = stmt.executeQuery(cmd);
if (rset.next()) {
blob = ((OracleResultSet)rset).getBLOB(2);
System.out.println("got blob reference");
}
    else System.out.println("no row to get!!!!");
    rset.close();
    blob = readFromFile();
    cmd = "update ImageTable set image = ? where column1 = 'one'";
PreparedStatement pstmt = conn.prepareStatement(cmd);
pstmt.setBlob(1, blob);
pstmt.execute();
stmt.execute("commit");
System.out.println("blob updated");
    blob = null;
    cmd = "select * from ImageTable for update";
rset = stmt.executeQuery(cmd);
if (rset.next()) {
System.out.println("get blob");
blob = ((OracleResultSet)rset).getBLOB(2);
// do something with blob
    }
    else
System.out.println("no row to get (2)!!!!");
  }
  catch (SQLException sqle) {
System.out.println("SQL Exception occured: " + sqle.getMessage());
sqle.printStackTrace();
  }
  catch(FileNotFoundException e) {
System.out.println("File Not Found");
  }
  catch (IOException ioe) {
System.out.println("IO Exception" + ioe.getMessage());
  }
  catch (Exception ioe) {
System.out.println("Exception" + ioe.getMessage());
  }
}
43. How do I enlist an Oracle XAResource?


This code will only work on the server side. It cannot be run in a client. Also note that enlistment is generally done transparently for JDBC resources that implement XAResource.

// Here is the XAResource for oracle
String URL = "jdbc:oracle:thin:@DbmsHost:DbmsPort:DbmsName";
DriverManager.registerDriver(new OracleDriver());
// Create XA Connection
OracleXADataSource oxds1 = new OracleXADataSource();
oxds1.setURL(URL);
oxds1.setUser("scott");
oxds1.setPassword("tiger");
javax.sql.XAConnection pc1 = oxds1.getXAConnection();
m_oracleResource = pc1.getXAResource ();
m_oracleConnection = pc1.getConnection();
// Here is the source code for getting the TM.
Context ctx = null;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
// Parameters for the WebLogic Server.
// Substitute the correct hostname, port number
// user name, and password for your environment:
env.put(Context.PROVIDER_URL, "t3://localhost:7001");
env.put(Context.SECURITY_PRINCIPAL, "system");
env.put(Context.SECURITY_CREDENTIALS, "managers");
ctx = new InitialContext(env);
m_tManager =
(TransactionManager)ctx.lookup("javax.transaction.TransactionManager");
//Here is the source code for registering the TM.
m_tManager.begin();
m_transaction = m_tManager.getTransaction();
weblogic.transaction.TransactionManager weblogicTManager =
((weblogic.transaction.TransactionManager) m_tManager);
weblogicTManager.registerStaticResource("oracle",m_oracleResource);
// enlist the resources with the transaction
m_transaction.enlistResource(m_oracleResource);
44. Why do I get "ORA-00600" ?


This error generally means that version of Oracle server is newer than version of the driver you are using. In case you are using the Oracle thin driver, you will need to download the latest ojdbc14.jar from Oracle and put it at the beginning of your CLASSPATH (and possibly update any scripts that start the server, such as startweblogic.cmd, since they override the CLASSPATH).


45. Why do I get "ORA-24327" ?


This error generally means that the environment ORACLE_HOME is not set or is set incorrectly or the D_LIBRARY_PATH or PATH does not include the right dynamic link libraries. It can also indicate a mismatch when trying to use weblogic.jdbc.oci.Driver with an earlier or later version of the Oracle client software than is supported. In that case, try to use the Oracle Thin driver instead.



46. Why do I get "java.sql.SQLException: getOBJECT is not supported by the WebLogic JDBC Driver"?


When using the WebLogic JDBC connection pool and weblogic.jdbc.vendor.oracle.OracleResultSet, the error is returned (where OBJECT is the name of some Oracle object). It implies that this feature is not supported by WebLogic Server JDBC because the object type is not serializable. There are two alternatives.

  • You can switch to using the Oracle thin driver directly. That means that you will get a connection directly to the database using the Thin driver instead of getting the connection from a pool of JDBC connections. That means that you lose all advantages of using the WebLogic Server JDBC subsystem, such as transactions, connection pooling, and caching of prepared statements.
  • BEA recommends moving your processing to a stored procedure.


47. Why do I get an "ORA-01453" when I use SET TRANSACTION?

When using Oracle, the message "java.sql.SQLException: ORA-01453: SET TRANSACTION must be first statement of transaction" may be logged. This is due to a limitation in the Oracle interfaces, starting in Oracle 8.1.7. WebLogic tries to minimize the problem by not calling SET TRANSACTION if the mode already matches the current state.