BEA Weblogic

  Home  Applications Programs  BEA Weblogic


“BEA Weblogic Interview Questions and Answers will guide us now that BEA Weblogic is a J2EE Application Server. It is used to host webpages from simple types to secured webpages. Technically, it is where all our JSP's, Servlets, EJB's etc. Are deployed. Advanced concepts like load balancing, clustering etc. Learn more about BEA Weblogic or get preparation for the job of BEA Weblogic with the help of this BEA Weblogic Interview Questions with Answers guide”



140 BEA Weblogic Questions And Answers

41⟩ How do I use JTA transactions within an MDB?

In the ejb-jar.xml file, define the transaction type as Container and the trans-attribute as Required, as in the following example:

<ejb-jar>

<enterprise-beans>

<message-driven>

<ejb-name>MDB</ejb-name>

<ejb-class>MDB</ejb-class>

<transaction-type>Container</transaction-type>

<message-driven-destination>

<destination-type>javax.jms.Queue</destination-type>

</message-driven-destination>

</message-driven>

</enterprise-beans>

<assembly-descriptor>

<container-transaction>

<method>

<ejb-name>MDB</ejb-name>

<method-name>*</method-name>

</method>

<trans-attribute>

Required

</trans-attribute>

</container-transaction>

</assembly-descriptor>

</ejb-jar>

To rollback a transaction, you can either use the WebLogic extension TXHelper or you can use the MDB context as in the following code examples:

UserTransaction ut =

weblogic.transaction.TXHelper.getUserTransaction();

ut.setRollbackOnly();

or

private MessageDrivenContext context;

public void setMessageDrivenContext(

MessageDrivenContext mycontext) {

context = mycontext;

}

public void onMessage(Message msg) {

try { // some logic

}

catch(Exception e) {

System.out.println("MDB doing rollback");

context.setRollbackOnly();

}

 159 views

43⟩ What is the NO_ACKNOWLEDGE acknowledge mode used for?

The NO_ACKNOWLEDGE acknowledge mode indicates that received messages do not need to be specifically acknowledged which improves performance, but risks that messages are lost. This mode is supported for applications that do not require the quality of service provided by session acknowledge and that do not want to incur the associated overhead. v Messages sent to a NO_ACKNOWLEDGE session are immediately deleted from the server. Messages received in this mode are not recovered and, as a result, messages may be lost and/or duplicate message may be delivered if an initial attempt to deliver a message fails.

Note: You should avoid using this mode if your application cannot handle lost or duplicate messages. Duplicate messages may be sent if an initial attempt to deliver a message fails.

In addition, we do not recommend that this acknowledge mode be used with persistent messaging, as it implies a quality of service that may be too low for persistent messaging to be useful.

 142 views

44⟩ When should I use server session pools and connection consumers?

WebLogic JMS implements an optional JMS facility for defining a server-managed pool of server sessions. This facility enables an application to process messages concurrently. A ConnectionConsumer object uses a server session to process received messages. If message traffic is heavy, the connection consumer can load each server session with multiple messages to minimize thread context switching. Multiple connection consumers can share server sessions in a server session pool.

To learn how to use the connection consumers within an application, see the section Processing Messages Concurrently in Programming WebLogic JMS, or the javax.jms.ConnectionConsumer javadoc.

Note: Server session pools can also be implemented using Message Driven Beans. Using MDBs is preferable to using server session pools - see the answer to the question, "How do server session pools and Message Driven Beans compare?" For information on using message driven beans to implement server session pools, see Programming WebLogic Enterprise JavaBeans.

 137 views

45⟩ How do I publish an XML message?

Follow these steps:

1. Generate XML from the DOM document tree.

2. Serialize the generated DOM document to a StringWriter.

3. Call toString on the StringWriter and pass it into message.setText.

4. Publish the message.

 152 views

46⟩ Is it possible to send or receive a message from within a message listener?

Yes. You can send to or receive from any queue or topic from within in a message listener.

If it's not an MDB, you can use the same Connection or Session that the onMessage() is part of to do this. When you create your message listener, you pass in a session in your constructor. Then you have access to the session in your onMessage method and you would be able to make synchronous, not asynchronous, calls from within the onMessage method. Do not use another Session that is servicing another onMessage() because that would multi-thread that Session and Sessions don't support multi-threading.

When things are done non-transactionally, there can be duplicates or lost messages (assuming your onMessage() code is attempting to forward messages):

1. If you call acknowledge after the publish() and the acknowledge fails for whatever reason (network/server failure), then you will see the message again and will end up publishing twice (possible duplicate semantics). You can try to keep track of sequence numbers to detect duplicates but this is not easy.

2. If you call acknowledge before the publish(), you get at-most-once semantics. If the publish() fails, you don't know if the failure occurred before or after the message reached the server.

If you want exactly once, transactional semantics using onMessage, you must use transactional MDBs. The onMessage() for a transactional MDB starts the transaction, includes the WebLogic Server JMS message received within that transaction and the publish() would also be in the same transaction. The following code sends a response to each message that it receives. It creates the connection, etc. in the ejbCreate method so that it doesn't need to create it every time onMessage is called. The QueueSender is anonymous (null Queue) since we don't know to whom we will have to reply. The ejbRemove method cleans up by closing the connection. This same approach can be used to create a receiver, subscriber or publisher.

import javax.ejb.CreateException;

import javax.ejb.EJBContext;

import javax.naming.*;

import javax.naming.directory.*;

import java.util.Hashtable;

import javax.ejb.MessageDrivenBean;

import javax.ejb.MessageDrivenContext;

import javax.jms.*;

public class MDB

implements MessageDrivenBean, MessageListener {

public static final String WLSqcf =

"javax.jms.QueueConnectionFactory";

public static final String WLSqname =

"jms.queue.TestQueue1";

public static final String WLSurl =

"t3://localhost:7001";

public static final String WLSJNDIfactory =

"weblogic.jndi.WLInitialContextFactory";

private MessageDrivenContext context;

private QueueSession session;

private QueueConnection connection = null;

private QueueConnectionFactory factory;

private InitialContext ctx;

private QueueSender QueueSender;

// Required - public constructor with no argument

public MDB() {}

// Required - ejbActivate

public void ejbActivate() {}

// Required - ejbRemove

public void ejbRemove() {

context = null;

if (connection != null) {

try {

connection.close();

} catch(Exception e) {}

connection = null;

}

}

// Required - ejbPassivate

public void ejbPassivate() {}

public void setMessageDrivenContext(

MessageDrivenContext mycontext) {

context = mycontext;

}

// Required - ejbCreate() with no arguments

public void ejbCreate () throws CreateException {

try {

// Get the initial context

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, WLSJNDIfactory);

env.put(Context.PROVIDER_URL, WLSurl);

env.put(Context.REFERRAL, "throw");

ctx = new InitialContext(env);

factory = (QueueConnectionFactory)ctx.lookup(WLSqcf);

// Create a QueueConnection, QueueSession, QueueSender

connection = factory.createQueueConnection();

session = connection.createQueueSession(false,

Session.AUTO_ACKNOWLEDGE);

queueSender = session.createSender(null);

connection.start();

} catch (Exception e) {

throw(new CreateException(e.toString()));

}

}

// Implementation of MessageListener

// Throws no exceptions

public void onMessage(Message msg) {

try {

System.out.println("MDB: " +

((TextMessage)msg).getText());

msg.clearBody();

((TextMessage)msg).setText("reply message");

queueSender.send((Queue)msg.getJMSReplyTo(), msg);

}

catch(Exception e) { // Catch any exception

e.printStackTrace();

}

}

}

This approach creates a connection per EJB/MDB instance, so you might want to create a producer pool that is shared by the EJB instances. This is done by writing a class that populates a static pool with producers (see the next question for a sample producer pool). The onMessage call grabs a producer when needed. Since Sessions must be single threaded, make sure there is only one producer per session within the producer pool.

 142 views

47⟩ What are pending messages in the console?

Pending means the message could have been:

* sent in a transaction but not committed.

* received and not acknowledged.

* received and not committed.

* subject to a redelivery delay (as of WebLogic Server 6.1).

* subject to a delivery time (as of WebLogic Server 6.1).

A rolled back message remains pending until the transaction actually rolls back. Rolling it back multiple times does not cause double counting, nor does an exception that set a transaction as rollbackOnly followed by an actual rollback.

Current implies messages that are not pending.

Total implies total since server last started. The byte counts only consider the payload of messages which includes the properties and the body but not the header.

 148 views

48⟩ Is it better to have more or fewer sessions for a given number of subscribers?

Using N sessions for N subscribers gives you concurrency up to N simultaneous threads of execution provided you have as many threads to work with. Each Session gets its own thread as long as there are enough threads available. Otherwise, the sessions serially reuse the available threads.

One session for N subscribers serializes all subscribers through that one session. If the load is heavy they may not be able to keep up without the extra threads.

If you are using CLIENT_ACKNOWLEDGE, N sessions gives you N separate message streams that can be individually recovered. Having one session crosses the streams giving you less control.

 164 views

49⟩ A client invokes a method on a stateful session bean instance deployed in the WebLogic Server. While the method execution is in progress another method call arrives on the server. What will be the result?

a. RemoteException is thrown if the value of concurrency-strategy property is false

b. EJBException is thrown if the value of concurrency-strategy property is false

c. The EJB container blocks the concurrent method call and allows it to proceed when the previous call has completed if the value of allow-concurrent-calls is true

d. In all cases, RemoteException is thrown

Choice C is correct. By default, simultaneous access to a stateful session EJB results in a RemoteException. However, you can set the allow-concurrent-calls option in the WebLogic EJB deployment descriptor to specify that a stateful session bean instance will allow concurrent method calls. This access restriction on stateful session EJBs applies whether the EJB client is remote or internal to WebLogic Server. By default, allows-concurrent-calls is false. However, when this value is set to true, the EJB container blocks the concurrent method call and allows it to proceed when the previous call has completed.

The concurrency-strategy element determines ejbLoad() and ejbStore() behavior for entity EJB instances.

 142 views

50⟩ What is the standard way to create threads, do initialization, etc. within the application server?

Threads should generally not be created by the user directly is because things may not work correctly. User-created threads do not have some of the thread-local variables pre-set by WebLogic when it creates it's own execute threads, the associated transaction context, or the environment such as the proper class loader. The WebLogic-specific way of doing this is with a startup class or using the WebLogic Time Services. The portable way to do this is to define a load-on-startup servlet, doing the initialization in the init() method and the cleanup in the destroy() method. The servlet itself does nothing. This approach also allows for undeploy/redeploy of the application without restarting the server, including proper cleanup/initialization each time. It also providers more dynamic management of the dependent classes without restarting the server.

 152 views

51⟩ How do I configure JMS security?

The correct way to set up security for JMS is to go to the console, select ACLs in the tree view, then create some access control lists.

1. Set the ACL name which should be weblogic.jms.queue.QUEUENAME or weblogic.jms.topic.TOPICNAME.

2. Select Create.

3. Enter the New Permission of send or receive.

4. Select Create.

5. Enter a comma separated list of users or groups.

6. Select Grant Permission.

7. Select "saved to the realm implementation" to save your changes.

8. Select Yes.

This will update the fileRealm.properties file with lines that look like the following:

acl.send.weblogic.jms.queue.TestQueue1=user1

acl.receive.weblogic.jms.queue.TestQueue1=user1

If you don't have an ACL for a queue or topic, security is wide open.

There are also ACL's for accessing the JNDI context; the JNDI context is a requirement for initially accessing JMS. See the JNDI documentation.

 131 views

52⟩ Why does JMSSession.createTopic or JMSSession.createQueue fail to create a destination in WLS JMS 6.1 (it worked in 5.1)?

In WLS 5.1 createTopic() or createQueue() creates the destination permanently in the database if it doesn't already exist, but does not modify the weblogic.properties file.

According to the JavaSoft JMS specification version 1.0.2 regarding createQueue() and createTopic(), they are not for creating destinations dynamically. They are used to retrieve the destination referenced by using a string name instead of using JNDI lookup. The destination has to be in your config.xml file first. This change is documented in WLS 6.0 since it behaves differently than the previous release. You can use the WLS JMS helper class (weblogic.jms.extensions.JMSHelper) or the console to create destinations at the run time (note that there was a bug in 6.0 that caused a problem when the server restarted; this is fixed in Service Pack 1). These mechanisms create the destination and also modify the configuration file.

For more information on the JMSHelper classes, see the subsection called Creating Destinations Dynamically in Programming WebLogic JMS.

The following program creates a Topic.

import java.io.*;

import java.util.Hashtable;

import javax.jms.*;

import javax.naming.*;

import weblogic.jms.extensions.JMSHelper;

class t {

public final static String

JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";

public final static String JMS_SERVER_NAME="TestJMSServer";

public final static String DEST_JNDI_PREFIX="javax.destination.";

static public void main(String [] args) throws Exception {

try {

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);

env.put(Context.PROVIDER_URL, "t3://localhost:7001");

Context ctx = new InitialContext(env);

String topicName = "JMSHelperTestQueue01";

String topicJNDI = DEST_JNDI_PREFIX + topicName;

System.out.println("topic name=" + topicName + ", jndi=" +

topicJNDI);

JMSHelper.createPermanentTopicAsync(ctx, JMS_SERVER_NAME,

topicName,

topicJNDI);

} catch (JMSException e) {

e.printStackTrace();

}

}

}

 148 views

53⟩ How do I use a temporary destination?

You must create a template on every JMSServer where you want to be able to create temporary destinations. You can specify multiple JMSServer entries to support TemporaryTemplate and the system will load balance among those JMS servers to setup the temporary destination. See How do I start WLS and configure JMS? for a description about how to configure JMS. The resulting template definition looks something like the following:

<JMSTemplate Name="MyTemplate"/>

The JMSServer is defined something like:

<JMSServer Name="MyJMSServer" TemporaryTemplate="MyTemplate" Targets="MyServer" >

After the template name, you can set any queue/topic attribute you want in the template (not including a JNDI name or topic multicast settings). The template is at the outer most level; that is, it should not be nested in your <JMSServer>.

Temporary destinations can only be consumed by the creating connection. Using topics, you create your temporary topic and subscribe to that temporary topic. If you want someone to publish to that temporary topic, you need to tell that someone what your topic is. You can send them a message and include your temporary topic in the JMSReplyTo field. The creator of the TemporaryTopic and the subscriber must be one in the same.

import javax.jms.TopicSession;

TemporaryTopic myTopic = mySession.createTemporaryTopic();

TopicSubscriber = mySession.createSubscriber(myTopic);

Temporary topics do not get names and cannot be subscribed to by other connections. When you create a temporary topic, the JMS provider returns a javax.jms.Topic. You then need to advertise that topic to other parties (those who want to publish to the topic), putting it in your JMSReplyTo field so that they can respond. In general, no one else can subscribe to the topic. You advertise the topic any way you want. Topics are serializable (or, in our case, externalizable), which allows you to pass them around in RMI calls, through a file, binding it to a name in JNDI, etc. In short, create the topic at the subscriber side and advertise so that others can publish. You can get multiple subscribers on the same connection and get concurrent processing using multiple sessions.

 153 views

54⟩ Which types of JDBC databases does WebLogic JMS support?

The JMS database can be any database that is accessible through a JDBC driver. WebLogic supports and provides JDBC drivers for the following databases:

* Cloudscape

* Informix

* Microsoft SQL (MSSQL) Server (Versions 6.5 and 7)

* Oracle (Version 8.1.6)

* Sybase (Version 12)

 148 views

55⟩ The Multicast TTL setting for a cluster in the WebLogic Admin console sets which of the following values?

The Multicast TTL setting for a cluster in the WebLogic Admin console sets which of the following values?

a. Maximum time taken for multicast messages to reach their final destination

b. The number of routers a multicast message can pass through before the packet can be discarded

c. The multicast address to be used by the messages sent from the cluster

d. Minimum time taken for broadcasting a multicast message from the cluster

Choice B is correct. The Multicast TTL(TTL-Time to Live) setting specifies the number of routers a multicast message can pass through before the packet can be discarded. To configure the multicast TTL for a cluster, you should change the Multicast TTL value in the WebLogic Server administration console. This sets the number of network hops a multicast message makes before the packet can be discarded.

If you choose to distribute a cluster over a WAN (or across multiple subnets), you must plan and configure your network topology to ensure that multicast messages are reliably transmitted to all servers in the cluster. One of the requirements to be met by the network is that the multicast Time To Live (TTL) value must be high enough to ensure that routers do not discard multicast packets before they reach their final destination.

 176 views

56⟩ How do I use persistence?

Use the following guidelines:

1. Make sure the JMSServer you are using has a store configured. The JMSServer configuration entry in the config.xml file should contain a line of the form

Store="<YOUR-STORE-NAME>"

Note that if JMS boots without a store configured, it is assumed the customer did not want one, and persistent messages are silently downgraded to non-persistent (as specified for JMS 1.0.2).

2. Make sure you are not using "Message.setJMSDeliveryMode". This is overwritten, as it is a vendor-only method.

3. Make sure you are calling either:

QueueSender.send(msg, deliveryMode, ...)

-- or --

QueueSender.setDeliveryMode(deliveryMode)

-- or --

set the DefaultDeliveryMode mode on connection factory in the config.xml file to persistent (the QueueSender.setDeliver/send overrides this value). Similarly, for topics, you would set this via the TopicPublisher.

4. Make sure you don't have "DeliveryModeOverride" set to Non-Persistent on the Destination in the config.xml file.

5. If you are using pub/sub, only durable subscriptions persist messages. Non-durable subscriptions have no need to persist messages, as by definition they only exist for the life of the server.

6. If you are using JDBC, the JDBC tables, JMSSTATE and JMSSTORE, are created automatically when the JMS server boots. The DDL files used to create the tables are stored in weblogic.jar in weblogic/jms/ddl. The example configuration below shows a JDBC store for Oracle (client version 8.1.7 or later is needed to run with WLS 6.1 on JDK 1.3). To manually create the tables (also deleting any existing tables), run java utils.Schema as described in the previous question.

See the question, "How do I start WLS and configure JMS?" for a description of how to configure JMS.

Here is a sample config.xml file resulting from configuring JMS. It should look similar to yours. If you want JMS to use a file store instead of a database, just change JDBCStore to FileStore in the JMSServer section.

<Server Name="myserver"

ListenPort="7001" DefaultProtocol="t3"

ThreadPoolSize="8" >

</Server>

<Security Realm="defaultRealm"

GuestDisabled="false" />

<Realm Name="defaultRealm"

FileRealm="defaultFileRealm" />

<FileRealm Name="defaultFileRealm"

/>

<JMSServer Name="TestJMSServer"

TemporaryTemplate="TestTemplate1"

Targets="myserver" Store="JDBCStore">

<JMSQueue Name="TestQueue1"

JNDIName="jms.queue.TestQueue1"

Template="TestTemplate1"

/>

</JMSServer>

<JMSTemplate Name="TestTemplate1"

/>

<JMSFileStore Name="FileStore"

Directory="myfilestore"

JMSServer="TestJMSServer"

/>

<JMSJDBCStore Name="JDBCStore"

ConnectionPool="testpool2"

JMSServer="TestJMSServer"

/>

<JDBCConnectionPool Name="testpool2"

Targets="myserver"

URL="jdbc:weblogic:oracle"

DriverName="weblogic.jdbc.oci.Driver"

InitialCapacity="0"

MaxCapacity="1"

CapacityIncrement="1"

Properties="user=SCOTT;password=tiger;server=bay816"

/>

</Domain>

The following is a sample class that sends

a Topic message on construction:

import javax.naming.*;

import javax.jms.*;

import java.util.Hashtable;

public class t

{

public final static String DESTINATION="jms.topic.TestTopic1";

private TopicConnectionFactory connectionFactory;

private TopicConnection connection;

private TopicSession session;

private TopicPublisher producer;

private TextMessage message;

private Topic destination;

public t()

{

try {

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY,

"weblogic.jndi.WLInitialContextFactory");

env.put(Context.PROVIDER_URL, "t3://localhost:7001");

InitialContext ctx = new InitialContext(env);

destination = (Topic) ctx.lookup(DESTINATION);

connectionFactory = (TopicConnectionFactory)

ctx.lookup("javax.jms.TopicConnectionFactory");

connection = (TopicConnection)

connectionFactory.createTopicConnection();

session = (TopicSession) connection.createTopicSession(false,

Session.AUTO_ACKNOWLEDGE);

producer = (TopicPublisher) session.createPublisher(destination);

producer.setDeliveryMode(DeliveryMode.PERSISTENT);

message = (TextMessage) session.createTextMessage();

message.setText("hello world");

producer.publish(message);

} catch (Exception e) {

}

}

}

 137 views

57⟩ How do the WLS JMS 6.1 server/destination message maximum and threshold values work?

The byte and message maximum values are quotas - not flow control. Message quotas prevent a WebLogic JMS server from filling up with messages and possibly running out of memory, causing unexpected results. When you reach your quota, JMS prevents further sends with a ResourceAllocationException (rather than blocking). You can set quotas on individual destinations or on a server as a whole.

The thresholds are also not flow control - though they would be better suited to that application than the quotas. The thresholds are simply settings that when exceeded cause a message to be logged to the console to let you know that you are falling behind.

Note that the messages maximum setting on a connection factory is not a quota. This specifies the maximum numbers of outstanding messages that can exist after they have been pushed from the server but before an asynchronous consumer has seen them; it defaults to a value of 10.

 144 views

58⟩ 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 unset, it defaults to a 7-bit ASCII character set, and tries to map characters greater than ASCII 128 to a reasonable approximation (for example, á, à, â would all map to a). Other characters are mapped to a question mark (?).

 139 views

59⟩ How many deployment descriptor files does a CMP entity bean deployed on the WebLogic Server have?

a. One J2EE specific deployment descriptor and two WebLogic specific deployment descriptors

b. One J2EE specific deployment descriptor and one WebLogic specific deployment descriptors

c. One J2EE specific deployment descriptor only

d. One WebLogic specific deployment descriptor only

Choice A is correct. Deployment descriptors are text documents formatted with XML tags. The J2EE specifications define standard, portable deployment descriptors for J2EE components and applications. BEA defines additional WebLogic-specific deployment descriptors required to deploy a component or application in the WebLogic Server environment.

When packaging an enterprise bean, we need to create an ejb-jar.xml deployment descriptor in the META-INF subdirectory and add entries for the bean. We also need to create a weblogic-ejb-jar.xml deployment descriptor in the META-INF subdirectory and add entries for the bean. If the bean is an entity bean with container-managed persistence, first we create a weblogic-rdbms-cmp-jar-bean_name.xml deployment descriptor in the META-INF directory with entries for the bean. Then we map the bean to this CMP deployment descriptor with a attribute in the weblogic-ejb-jar.xml file.

 148 views

60⟩ 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(?))";

 173 views