Friday, 15 November 2013

How to delete a Broker from the Toolkit in Windows 7/MB 8.0.0.1

Step 1:- Goto "C:\Program Files (x86)\IBM\WebSphere MQ\Qmgrs" & remove the queue manager that is assosciated with that broker first.

Step 2:- The Goto "C:\ProgramData\IBM\MQSI\components" & remove all the log file present in that components folder.

C:\ProgramData\IBM\MQSI
There remove the Broker name in the Common,Config,registry folders

Thats All you are done deleting an unwanted broker in MB8..!



WebSphere MQ commands
 -----------------------------------------------

amqccert - Check certificate chains

amqmdain - WebSphere MQ services control

amqtcert - Transfer certificates

crtmqm - Create Queue Manager

dltmqm - Delete queue manager

dmpmqaut - Dump authority

dmpmqlog - Dump log

dspmq - Display Queue Managers

dspmqaut - Display authority

dspmqcsv - Display command server

dspmqfls - Display files

dspmqrte - WebSphere MQ display route application

dspmqtrc - Display formatted trace output

dspmqtrn - Display transactions

dspmqver - Display version information

endmqcsv - End command server

endmqlsr - End listener

endmqdnm - Stop .NET monitor

endmqm - End Queue Manager

endmqtrc - End trace

mqftapp - Run File Transfer Application GUI
   
mqftrcv - Receive file on server

mqftrcvc - Receive file on client

mqftsnd - Send file from server

mqftsndc - Send file from client

rcdmqimg - Record media image

rcrmqobj - Recreate object

rsvmqtrn - Resolve transactions

runmqchi - Run channel initiator

runmqchl - Run channel

runmqdlq - Run dead-letter queue handler

runmqdnm - Run .NET monitor

runmqlsr - Run listener

runmqsc - Run MQSC commands

runmqtmc - Start client trigger monitor

runmqtrm - Start trigger monitor

setmqaut - Set or reset authority

setmqcrl - Set certificate revocation

setmqscp - Set service connection points

strmqcfg - Start WebSphere MQ Explorer

strmqcsv - Start command server

strmqm - Start Queue Manager

strmqtrc - Start trace
Distribution using Commands
---------------------------------------------------
C:\Documents and Settings\miracle>CRTMQM QM1
WebSphere MQ queue manager created.
Directory 'C:\Program Files\IBM\WebSphere MQ\qmgrs\QM1' created.
Creating or replacing default objects for QM1.
Default objects statistics : 68 created. 0 replaced. 0 failed.
Completing setup.
Setup completed.

C:\Documents and Settings\miracle>strmqm QM1
WebSphere MQ queue manager 'QM1' starting.
5 log records accessed on queue manager 'QM1' during the log replay phase.
Log replay for queue manager 'QM1' complete.
Transaction manager state recovered for queue manager 'QM1'.
WebSphere MQ queue manager 'QM1' started.

C:\Documents and Settings\miracle>runmqsc QM1
5724-H72 (C) Copyright IBM Corp. 1994, 2009.  ALL RIGHTS RESERVED.
Starting MQSC for queue manager QM1.


define Listener(ch1) trptype(tcp) port(1000)
     1 : define Listener(ch1) trptype(tcp) port(1000)
AMQ8626: WebSphere MQ listener created.

START Listener(ch1)
     2 : START liSTENER(ch1)
AMQ8021: Request to start WebSphere MQ Listener accepted.

Define channel(sr) chltype(SDR) trptype(tcp) conname('localhost(2000)') xmitq(trq)
     3 : Define channel(sr) chltype(SDR) trptype(tcp) conname('localhost(2000)')xmitq(trq)
AMQ8014: WebSphere MQ channel created.

define qlocal(trq) usage(xmitq)
     4 : define qlocal(trq) usage(xmitq)
AMQ8006: WebSphere MQ queue created.

define Qremote(rq1) rqmname(QM2) rname(lq1) xmitq(trq)
     5 : define Qremote(rq1) rqmname(QM2) rname(lq1) xmitq(trq)
AMQ8006: WebSphere MQ queue created.

       :
end
     6 : end
5 MQSC commands read.
No commands have a syntax error.
All valid MQSC commands were processed.

-----------------------------------------------------------------------------------------------------
Now the 2nd QMgr is to be created

C:\Documents and Settings\miracle>crtmqm QM2
WebSphere MQ queue manager created.
Directory 'C:\Program Files\IBM\WebSphere MQ\qmgrs\QM2' created.
Creating or replacing default objects for QM2.
Default objects statistics : 68 created. 0 replaced. 0 failed.
Completing setup.
Setup completed.

C:\Documents and Settings\miracle>strmqm QM2
WebSphere MQ queue manager 'QM2' starting.
5 log records accessed on queue manager 'QM2' during the log replay phase.
Log replay for queue manager 'QM2' complete.
Transaction manager state recovered for queue manager 'QM2'.
WebSphere MQ queue manager 'QM2' started.

C:\Documents and Settings\miracle>runmqsc QM2
5724-H72 (C) Copyright IBM Corp. 1994, 2009.  ALL RIGHTS RESERVED.
Starting MQSC for queue manager QM2.


define Qlocal(lq1)
     1 : define Qlocal(lq1)
AMQ8006: WebSphere MQ queue created.

define Listener(ch1) trptype(tcp) port(2000)
     2 : define Listener(ch1) trptype(tcp) port(2000)
AMQ8626: WebSphere MQ listener created.

start listener(ch1)
     3 : start listener(ch1)
AMQ8021: Request to start WebSphere MQ Listener accepted.

Define Channel(sr) chltype(rcvr) trptype(tcp)
     4 : Define Channel(sr) chltype(rcvr) trptype(tcp)
AMQ8014: WebSphere MQ channel created.

end
     5 : end
4 MQSC commands read.
No commands have a syntax error.
All valid MQSC commands were processed.

C:\Documents and Settings\miracle>rummqsc QM1
'rummqsc' is not recognized as an internal or external command,
operable program or batch file.

C:\Documents and Settings\miracle>runmqsc QM1
5724-H72 (C) Copyright IBM Corp. 1994, 2009.  ALL RIGHTS RESERVED.
Starting MQSC for queue manager QM1.


start channel(sr)
     1 : start channel(sr)
AMQ8018: Start WebSphere MQ channel accepted.

end
     2 : end
One MQSC command read.
No commands have a syntax error.
All valid MQSC commands were processed.


C:\Documents and Settings\miracle>amqsput RQ1 QM1
Sample AMQSPUT0 start
target queue is RQ1
Miracle Software Systems
Sample AMQSPUT0 end

C:\Documents and Settings\miracle>amqsget LQ1 QM2
Sample AMQSGET0 start
Message <Miracle Software Systems>
no more messages
Sample AMQSGET0 end

Hibernate Hello World Program (Hibernate Insert Query)





Lets have a look at the first program in hibernate like saving an object into the database (don’t think we are inserting a record into the database that is the case in JDBC, in hibernate we are just saving an object into database, means inserting only) hope you got my contention,  as of now am giving this as normal console based java application, actually it’s bit tedious to set the class path every time for all the jar files but you must know this too.
From the next example i will give all the applications in the Eclipse
As i told you earlier,  these are the files we require to shape an hibernate program..
  • Product.java (My POJO class)
  • Product.hbm.xml  (Xml mapping file )
  • hibernate.cfg.xml  (Xml configuration file)
  • ClientForSave.java (java file to write our hibernate logic)


Product.java:

private int productId;
private String proName;
private double price;
public void setProductId(int productId)
{
this.productId = productId;
}
public int getProductId()
{
return productId;
}
public void setProName(String proName)
{
this.proName = proName;
}
public String getProName()
{
return proName;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}










Product.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Product" table="PRODUCTS">
<id name="productId" column="pid" >
<generator class="assigned" />
</id>
<property name="proName" column="pname" />
<property name="price"/>
</class>
</hibernate-mapping>


In this mapping file, my Product class is linked with PRODUCTS table in the database, and next is the id element, means in the database table what column we need to take as primary key column, that property name we need to give hear, actually i have been given my property name productId which will mapped with pid column in the table.
And proName is mapped with pname column of the PRODUCTS table, see i have not specified any column for the property price, this means that, our property name in the pojo class and the column name in the table both are same.
Remember: the first 3 lines is the DTD for the mapping file, as a programmer no need to remember but we need to be very careful while you are copying this DTD, program may not  be executed if you write DTD wrong, actually we have separate DTD’s for Mapping xml and Configuration xml files.

hibernate.cfg.xml:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property>
<property name="connection.user">user</property>
<property name="connection.password">password</property>
<!-- Related to the connection END -->
<!-- Related to hibernate properties START -->
<property name="show_sql">true </property>
<property name="dialet">org.hibernate.dialect.OracleDialect </property>
<property name="hbm2ddl.auto">update </property>
<!-- Related to hibernate properties END -->
<!-- Related to mapping START -->
<mapping resource="product.hbm.xml" />
<!-- Related to the mapping END -->
</session-factory>
</hibernate-configuration>


In this configuration file i have been given my Oracle database connection properties, if you are using MySql then just specify your database related details actually its depends on you.

ClientForSave.java

import org.hibernate.*;
import org.hibernate.cfg.*;
public class ClientForSave {
public static void main(String[] args)
{
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Product p=new Product();
p.setProductId(101);
p.setProName("iPhone");
p.setPrice(25000);
Transaction tx = session.beginTransaction();
session.save(p);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}


Now compile all .java files and run ClientForSave.java and check the output

Output Eclipse







In the database:


Note:
  • Make sure all .class, .java, .xml files are exist in the same folder
  • Before you compile and run this application, ensure you set the class path for all 12 jars files, this is tedious like what i told you earlier, we can avoid this process from the next example with Eclipse, a real time tool
  • except select operation, all other operations must be in the Transaction Scope


What is Hibernate – Hibernate Introduction








In this tutorial we will see why Hibernate came into picture though we have JDBC for connecting to the database, and what is this hibernate frame work first let us see what are the draw backs of JDBC

Draw Backs of JDBC:

  • In JDBC, if we open a database connection we need to write in try, and if any exceptions occurred catch block will takers about it, and finally used to close the connections.
  • Hear as a programmer we must close the connection, or we may get a chance to get our of connections message…!
  • Actually if we didn’t close the connection in the finally block, then jdbc doesn’t responsible to close that connection.
  • In JDBC we need to write Sql commands in various places, after the program has created if the table structure is modified then the JDBC program doesn’t work, again we need to modify and compile and re-deploy required, which is tedious.
  • JDBC used to generate database related error codes if an exception will occurs, but java programmers are unknown about this error codes right.
  • In the Enterprise applications, the data flow with in an application from class to class will be in the form of objects, but while storing data finally in a database using JDBC then that object will be converted into text.  Because JDBC doesn’t transfer objects directly.
In order to overcome above problems,  Hibernate came into picture..!

What is Hibernate:

Hibernate is the ORM tool given to transfer the data between a java (object) application and a database (Relational) in the form of the objects.  Hibernate is the open source light weight tool given by Gavin King, actually JBoss server is also created by this person only.
Hibernate is a non-invasive framework,  means it wont forces the programmers to extend/implement any class/interface, and in hibernate we have all POJO classes so its light weight.
Hibernate can runs with in or with out server, i mean it will suitable for all types of java applications (stand alone or desktop or any servlets bla bla.)
Hibernate is purely for persistence (to store/retrieve data from Database).

Mapping And Configuration Files In Hibernate







Mapping and Configuration are very familiar keywords we used to hear in the hibernate, every hibernate program must need these 2 xml files.

Mapping:

  • Mapping file is the heart of hibernate application.
  • Every ORM tool needs this mapping, mapping is the mechanism of placing an object properties into column’s of a table.
  • Mapping can be given to an ORM tool either in the form of an XML or in the form of the annotations.
  • The mapping file contains mapping from a pojo class name to a table name and pojo class variable names to table column names.
  • While writing an hibernate application, we can construct one or more mapping files, mean a hibernate application can contain any number of  mapping files.
generally an object contains 3 properties like
  • Identity (Object Name)
  • State (Object values)
  • Behavior (Object Methods)
But while storing an object into the database, we need to store only the values(State) right ? but how to avoid identity, behavior.. its not possible. In order to inform what value of an object has to be stored in what column of the table, will be taking care by the mapping,  actually mapping can be done using 2 ways,
  • XML
  • Annotations.
Actually annotations are introduced into java from JDK 1.5.

Syntax Of Mapping xml:

<hibernate-mapping> <class name="POJO class name" table="table name in database"> <id name="variable name" column="column name in database" type="java/hibernate type" /> <property name="variable1 name" column="column name in database" type="java/hibernate type" /> <property name="variable2 name" column="column name in database" type="java/hibernate type" /> </class> </hibernate-mapping>
1
2
3
4
5
6
7
8
9
<hibernate-mapping>

<class name="POJO class name" table="table name in database">
<id name="variable name" column="column name in database" type="java/hibernate type" />
<property name="variable1 name" column="column name in database" type="java/hibernate type" />
<property name="variable2 name" column="column name in database" type="java/hibernate type" />
</class>

</hibernate-mapping>


Configuration:

Configuration is the file loaded into an hibernate application when working with hibernate, this configuration file contains 3 types of information..
  • Connection Properties
  • Hibernate Properties
  • Mapping file name(s)
We must create one configuration file for each database we are going to use, suppose if we want to connect with 2 databases, like Oracle, MySql, then we must create 2 configuration files.
No. of databases we are using  = That many number of configuration files
We can write this configuration in 2 ways…
  • xml
  • By writing Properties file.  We don’t have annotations hear, actually in hibernate 1, 2.x we defined this configuration file by writing .properties file, but from 3.x xml came into picture.
so, finally
Mapping –> xml, annotations
Configuration –> xml, .properties (old style)

Syntax Of Configuration xml:

<hibernate-configuration> <session-factory> <!-- Related to the connection START --> <property name="connection.driver_class">Driver Class Name </property> <property name="connection.url">URL </property> <property name="connection.user">user </property> <property name="connection.password">password</property> <!-- Related to the connection END --> <!-- Related to hibernate properties START --> <property name="show_sql">true/false</property> <property name="dialet">Database dialet class</property> <property name="hbm2ddl.auto">create/update or what ever</property> <!-- Related to hibernate properties END--> <!-- Related to mapping START--> <mapping resource="hbm file 1 name .xml" / > <mapping resource="hbm file 2 name .xml" / > <!-- Related to the mapping END --> </session-factory> </hibernate-configuration>























<hibernate-configuration>
<session-factory>

<!-- Related to the connection START -->
<property name="connection.driver_class">Driver Class Name </property>
<property name="connection.url">URL </property>
<property name="connection.user">user </property>
<property name="connection.password">password</property>
<!-- Related to the connection END -->

<!-- Related to hibernate properties START -->
<property name="show_sql">true/false</property>
<property name="dialet">Database dialet class</property>
<property name="hbm2ddl.auto">create/update or what ever</property>
<!-- Related to hibernate properties END-->

<!-- Related to mapping START-->
<mapping resource="hbm file 1 name .xml" / >
<mapping resource="hbm file 2 name .xml" / >
<!-- Related to the mapping END -->

</session-factory>
</hibernate-configuration>


But XML files are always recommended to work.

Steps to Create your own run commands


Step 1. The first step is to select the software or application for which you want to make custom Run command. For example, let us consider Google Chrome as the example here. Remember, you can choose any application other than which is already there in the Run command.

Step 2. In the second step, right click on the desktop of your computer system and make a new shortcut.
Right click > New > Shortcut

Step 3. As you select the Shortcut option in the 2nd Step, it will open up a dialog box. And, the dialog box will ask you path of the application or software for which you want to create the Run command.

Step 4. Now, you need to browse through the files and choose the one that shows “chrome.exe”. Well, it is quite obvious that all the executable files can be found in the C drive (or wherever the Operating System has been installed), inside the folder “Program Files”. For example, “C:\Program Files\Google Chrome\chrome.exe

Step 5. Once you are done with Step number 4, just click on “Next” button and simply provide a relative name to that shortcut. Remember, the same name will be used later in the Run command.
For example, “GC” for Google Chrome

Step 6. Now, click on the “Finish” button. Once it is done, an icon related to that application or software will show up on your computer’s screen. It means that the process of creating shortcut has been done successfully.

Step 7. In this step, just cut and paste that recently made shortcut icon into your computer’s root drive, in its Windows folder.
For example, C:\ Windows , Make sure you are the administrator of the computer or have its password.

Step 8. Now, you are done with the set up and can run the application through Run Command. Just go to Run and enter the keyword “GC”, and Google Chrome will begin executing.

Friday, 1 November 2013

How to Remove Genuine Windows 7

Following three simple steps now you can get rid of the pesky and sometimes buggy Windows Genuine Advantage (WGA) notifications:

1. Reboot Windows in safe mode (hold the f8 key while booting and you will get the option to boot in safe mode) and then:

2. Open Registry Editor (regedit.exe) and search for wgalogon folder and delete it. You should backup up the registry beforehand, in case somethiong goes wrong.

3. In your windows directory search for files wga* and delete them.
You are done!

Now reboot back normally and continue your work. Windows Genuine Advantage will not bother you anymore.
Note: I had previously posted a tip which requires a third-party executable. Now it is not required anymore. You can do it yourself by carefully following the guide above.
Warning: Use at your own risk. Backup everything before you do.
Concept of UDP's in Message Broker

1.If we specified in the message flow's User defined properties panel some values like dsn,schema then in the flow we need to declare using 'EXTERNAL' keyword & give some null values within single quotes.The values that we mention in the ESQL code are not effected with the values in the Message flow USer defined properties panle.

Ex:- DECLARE cDATABASE EXTERNAL CHARACTER '';

2. No need to create UDP in flow but using ESQL coding we can create UDP

Ex:-DECLARE cDATABASE EXTERNAL CHARACTER 'EAI';
WebSphere Message Broker V8 .NET integration
-----------------------------------------------
.Net Compute Node is a newly added node in Message Broker V8.

Prerequisites:-
 1.MicrosoftVisual Studio installed
 2..dll file generated from the Visual Studio.

Then we need to specify that .dll file in the .Net Compute Node property

For a clear understanding,look into this link:-
http://www.youtube.com/watch?v=gHFHbm9jhNU


Basic Studio Tutorial In Mule Studio

This exercise is designed to introduce you to Mule Studio and help you get comfortable building applications.
This tutorial walks you through how to use Mule Studio to build a simple HTTP request-response application. After creating and running the example locally, you will be able to apply what you have learned to create more complex applications.

Assumptions

This tutorial assumes that you have downloaded and installed Mule Studio. If you do not have any previous experience with Eclipse or an Eclipse-based IDE, please review the brief introduction to the Mule Studio interface.

Goals

In this tutorial, your goals are to:
  1. Create an application in Mule Studio containing a single flow that
    • receives an HTTP request, 
    • logs the message payload, and 
    • returns a modified payload as an HTTP response.
  2. Run the application on a local runtime embedded in Mule Studio.
  3. Test the application using your browser. 
  4. Stop the application.
  5. Edit the application and rerun it.
  6. (Optional) Apply your knowledge to an extra credit challenge.

Skip to the code


Launching Studio

If you have already launched Studio as part of the installation process, and it is now running, skip the rest of this section and proceed directly to Creating a New Project.
  1. Navigate to the directory on your local drive in which you installed Studio.
  2. Double-click the executable file to launch Studio.
    • MuleStudio.exe in Windows
    • MuleStudio.app in Mac OS
    • MuleStudio in Linux
       
  3. When Studio presents the Workspace Launcher dialog, click OK to accept the default workspace. 
  4. If this is the first time you have launched Studio, you may see a Welcome screen. Click Create a Project to dismiss the screen and jump straight to the New Mule Project wizard.

Creating a New Project

  1. Unless the New Project Wizard is already open, click File > New > Mule Project.
  2. Studio opens the New Mule Project wizard. Fill in the Name field with the value Basic Tutorial.
  3. Select the Server Runtime to which you will want to deploy your project. Mule Studio automatically populates the Server Runtime field with one of the default servers that comes bundled with your download. You can change to a different runtime if you wish, but this project will work with any runtime. For more about installing additional runtime versions, see Installing Extensions.

  4. Click Next to proceed.
  5. Studio prompts you to create a new flow in your new project. It auto-fills the flow Name field and flow File name field using the name of the Mule project you entered. Click Finish.
  6. In the Package Explorer, Basic Tutorial.mflow appears inside the flows folder and mule-project.xml appears underneath the src folder. 



    The .mflow file stores flow information for the visual editor. When your new project opens for the first time, Mule Studio automatically opens the .mflow file and presents you with a blank canvas.

 Find out more about the .mflow and mule-project.xml files

Modeling a Mule Flow

In this tutorial, your goal is to build an application that receives an HTTP request, logs the message payload, and then modifies the payload before returning it as an HTTP response. You can build this application using three building blocks in Studio:
  • an HTTP endpoint, which allows your Mule application to connect to Web resources through the HTTP or HTTPS protocol. Find this in the Endpoints section of the palette at the right of the screen. 
  • a Logger, which logs messages or activity based on the value of a Mule expression. Find this in the Components section of the palette at the right of the screen. 
  • Set Payload Transformer, which modifies your payload into a "Hello, World" message. Find this in the Transformers section of the palette at the right of the screen. 
Drag and drop these three building blocks into place on the canvas to visually construct, or model, your flow, in the order shown:


 More detailed instructions
Tip: Use the Palette Filter
Note that building blocks in each category of the palette are organized alphabetically. To avoid scrolling, use the Filter tool in the upper right corner of the palette to find the building blocks that you want more quickly.
With just a few clicks, you have modeled your entire application on the Studio canvas.
Once you configure the individual elements within it, which you will do in the next section, this flow will accomplish the goals that you set out to achieve with this application. Each building block that you selected and placed on the canvas will perform part of the functionality of your application, as shown in the image below.


Configuring the Flow Elements

Nearly all Mule elements provide configuration options, which you can set in one of two ways:
  • via the building block Properties tabs in Studio's visual editor
  • via XML code in Studio's XML editor
The following instructions introduce you to configuring in both editors.
  1. Click the HTTP building block in your flow to open its properties editor. (Depending on your settings, this may open in a pop-up or in the console.) By default, the endpoint is set to the request-response exchange pattern. This means that Mule will return a response to the endpoint after processing is complete in the flow. By default, Host is set to localhost and Port to 8081.

  2. Click Configuration XML at the bottom of the canvas to switch to the XML editor view.


    Observe that the default configurations shown on the Message Flow canvas and the Configuration XML view are the same:
    <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" doc:name="HTTP"/>
    The doc:name attribute corresponds to the display name that appears underneath the building block icon on the Message Flow canvas. 
  3. Still in the XML configuration view, change the value of the port attribute to 8084
  4. Click Message Flow to switch back to the visual editor.

      
  5. Click the HTTP building block to reopen its properties tab, and note that the Port field now reflects the updated value of 8084. You can change this value in either editor; Studio's two-way editor automatically updates the configuration as you switch back and forth.

  6. Click the Logger building block (or press the right arrow on your keyboard) to switch the properties tab to the Logger component.
  7. In the Message field, type: Current payload is #[message.payload].



    The string #[message.payload] is a simple Mule expression which evaluates to the current payload of the message as it passes this point in the flow. Including this message here instructs Mule to log this information in the application log files, which can be useful in more complex use cases, when you need to track the payload at different points in your flow.
  8. Click the Set Payload building block (or press the right arrow on your keyboard) to switch the properties tab to the Set Payload transformer.
  9. Notice that the Value field contains these characters: #[]



    This indicates that this field supports Mule expressions, which take the form of a string enclosed with "#[]". If you enter a Mule expression here, Mule evaluates it at runtime and returns or uses the results for further processing. Note that this field also accepts literals, so you can enter any string here to instruct Mule to set that string as your new payload. In this tutorial, however, you will use an expression to create a dynamic message.
  10. In the Value field, enter:
    #['Hello, ' + message.payload + '. Today is ' + server.dateTime.format('dd/MM/yy') + '.' ]

    Note that message.payload and server.dateTime.format('dd/MM/yy') are both Mule expressions. Because you are entering them within a larger Mule expression, the #[] syntax is not required around these individual expressions. Anything that you enter inside of the "#[]" syntax which is not a Mule expression must be enclosed with quotes so that Mule reads it as a string.
  11. Save your application by clicking File > Save.


Your complete application XML, once configured, should look like this:
<?xml version="1.0" encoding="UTF-8"?>
    <flow name="Basic_TutorialFlow1" doc:name="Basic_TutorialFlow1">
        <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8084" doc:name="HTTP"/>
        <logger message="Current payload is #[message.payload]" level="INFO" doc:name="Logger"/>
        <set-payload value="#['Hello, ' + message.payload + '. Today is ' + server.dateTime.format('dd/MM/yy') + '.']" doc:name="Set Payload"/>
    </flow>
</mule>

Running the Application

Having built, configured, and saved your new application, you are ready to run it on the embedded Mule server (included as part of the bundled download of Mule Studio).
  1. In the Package Explorer pane, right-click the Basic Tutorial.mflow file, then select Run As > Mule Application. (If you have not already saved, Mule prompts you to save now.)

  2. Mule immediately kicks into gear, starting your application and letting it run. When the startup process is complete, Studio displays a message in the console that reads, Started app 'basic_tutorial'.


Using the Application

  1. Open any Web browser and go to http://localhost:8084/world
  2. Your browser presents a message that reads, Hello, /world. Today is [today's date].
  3. In your browser’s address bar, replace the word world with your own name, then press enter.
  4. Your browser presents the same message, but includes your name instead of "world".

  5. Next, check your console in Mule Studio to verify that Mule logged the payload before the message reached the expression transformer. 
  6. Place your cursor in the console window, press CTRL+F or COMMAND+F to open a Find dialog, and search for "Current payload". Look for results corresponding to the payloads that you entered in your browser. For example:

    INFO  2013-08-21 09:22:26,446 [[basic_tutorial].connector.http.mule.default.receiver.02] org.mule.api.processor.LoggerMessageProcessor: Current payload is /Aaron
    You may also see some other results for a payload of "/favicon.ico". These results are automatically generated by your browser. You can filter out these results in the Editing the Application section, below.
Congratulations! You've run and tested your application. You submitted a request to the inbound endpoint of your application via your Web browser. The Mule application received your request and logged the payload (whatever you typed after "http://localhost:8084/") to the console. The application then sent the message on to the Set Payload transformer, which transformed the payload per its instructions and returned the results to your HTTP endpoint.

Stopping the Application

To stop the application, click the red, square Terminate icon above the console panel.



Editing the Application

You may have noticed that your browser inserts an additional payload of "/favicon.ico" upon each refresh. You can add a filter element into your flow to exclude these payloads. Here's how:
  1. Drag and drop an Expression Filter from the Filters section of the palette onto your canvas, positioning it between the HTTP endpoint and the Logger.

  2. Click the Expression Filter to open its properties tab and enter the following in the Expression field:
    #[message.payload != '/favicon.ico']
    This expression tells Mule to check that the payload is not equal to the string '/favicon.ico'. If the expression evaluates to true, Mule passes the message on to the next step in the flow. If the expression evaluates to false, Mule stops processing the message.
  3. Save your application and run it again. (Right-click Basic Tutorial.mflow in your Package Explorer, then click Run As > Mule Application.)
  4. Wait for the message in the console that reads, Started app 'basic_tutorial'.
  5. Return to your Web browser and go to http://localhost:8084/world
  6. Replace "world" with another word of your choice and refresh. Repeat this step several times with different words.
  7. Check the logged payloads in your console: place your cursor in the console window, press CTRL+F or COMMAND+F to open a Find dialog, and search for "Current payload".
  8. All payloads that you see should correspond to the words you entered in your browser, and "/favicon.ico" should no longer be included. 

Your complete application XML, once edited, should look like this:
<?xml version="1.0" encoding="UTF-8"?>
    <flow name="Basic_TutorialFlow1" doc:name="Basic_TutorialFlow1">
        <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8084" doc:name="HTTP"/>
        <expression-filter expression="#[message.payload != '/favicon.ico']"  doc:name="Expression"/>
        <logger message="Current payload is #[message.payload]" level="INFO" doc:name="Logger"/>
        <set-payload value="#['Hello, ' + message.payload + '. Today is ' + server.dateTime.format('dd/MM/yy') + '.']" doc:name="Set Payload"/>
    </flow>
</mule>
JSP and JDBC Questions
  1. What is the query used to display all tables names in SQL Server (Query analyzer)?
    select * from information_schema.tables
  2. How many types of JDBC Drivers are present and what are they? 
     There are 4 types of JDBC Drivers
    • JDBC-ODBC Bridge Driver
    • Native API Partly Java Driver
    • Network protocol Driver
    • JDBC Net pure Java Driver
  3. Can we implement an interface in a JSP? 
     No
  4. What is the difference between ServletContext and PageContext? 
     ServletContext: Gives the information about the container. PageContext: Gives the information about the Request
  5. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
      request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.
  6. How to pass information from JSP to included JSP? 
     Using <%jsp:param> tag.
  7. What is the difference between directive include and jsp include? 
     <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime.
  8. What is the difference between RequestDispatcher and sendRedirect? 
     RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.
  9. How does JSP handle runtime exceptions? 
    Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.
  10. How do you delete a Cookie within a JSP?
    Cookie mycook = new Cookie("name","value");
  11.  response.addCookie(mycook);
  12. Cookie killmycook = new Cookie("mycook","value");
  13. killmycook.setMaxAge(0);
  14. killmycook.setPath("/");
  15.  killmycook.addCookie(killmycook);
  16. How do I mix JSP and SSI #include? 
     If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.
    <!--#include file="data.inc"---
  1. I made my class Cloneable but I still get Can’t access protected method clone. Why? 
     Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone().
  2. Why is XML such an important development? 
    It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.
  3. What is the fastest type of JDBC driver? 
    JDBC driver performance will depend on a number of issues:
    • the quality of the driver code,
    • the size of the driver code,
    • the database server and its load,
    • network topology,
    • the number of times your request is translated to a different API.
In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
  1. How can I send user authentication information while makingURLConnection? 
     You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.


                                                J2EE EJB Questions
  1. What is the relationship between local interfaces and container-managed relationships? - Entity beans that have container-managed relationships with other entity beans, must be accessed in the same local scope as those related beans, and therefore typically provide a local client view. In order to be the target of a container-managed relationship, an entity bean with container-managed persistence must provide a local interface.
  2. What does a remove method do for different cases of beans? - Stateless Session : Does not do anything to the bean as moving the bean from free pool to cache are managed by the container depending on load. Stateful Session: Removes the bean from the cache. Entity Bean: Deletes the bean (data) from persistent storage
  3. How does a container-managed relationship work? - An entity bean accesses related entity beans by means of the accessor methods for its container-managed relationship fields, which are specified by the cmr-field elements of its abstract persistence schema defined in the deployment descriptor. Entity bean relationships are defined in terms of the local interfaces of the related beans, and the view an entity bean presents to its related beans is defined by its local home and local interfaces. Thus, an entity bean can be the target of a relationship from another entity bean only if it has a local interface.
  4. What is the new basic requirement for a CMP entity bean class in 2.0 from that of ejb 1.1? - It must be abstract class. The container extends it and implements methods which are required for managing the relationships
  5. What are the basic classes required in the client for invoking an EJB? - The home and the remote interfaces, the implementation of the Naming Context Factory, the stubs and skeletons. In some App servers the stubs and the skeletons can be dynamically downloaded from the server
  6. What is the difference between Message Driven Beans and Stateless Session beans? - In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways:
    1. Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.
    2. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic.
    3. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary.
    4. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.
  7. What is the need for Clustering? - To scale the application so that it is highly available and has high throughput.
  8. What are the benefits of Clustering and workload management? - They are
    1. It balances client processing requests, allowing incoming work requests to be distributed according to a configured Workload Management selection policy.
    2. It provides fail over capability by redirecting client requests to a running server when one or more servers are unavailable. This improves the availability of applications and administrative services.
    3. It enables systems to be scaled up to serve a higher client load than provided by the basic configuration. With server groups and clones additional instances of servers can easily be added to the configuration.
    4. It enables servers to be transparently maintained and upgraded while applications remain available for users.
    5. It centralizes administration of application servers and other objects.
  9. What are the types of Scaling? - There are two types of scaling: Vertical Scaling and Horizontal Scaling.
  10. What is Vertical Scaling? - When multiple server clones of an application server are defined on the same physical m/c, it is called Vertical Scaling. The objective is to use the processing power of that m/c more efficiently.
  11. What is Horizontal Scaling? - When Clones of an application server are defined on multiple physical m/c, it is called Horizontal Scaling. The objective is to use more than one less powerful m/c more efficiently.
  12. What is a Server Group? - A server group is a template of an Application Server(and its contents) i.e, it is a logical representation of the application server. It has the same structure and attributes as the real Application Server, but it is not associated with any node, and does not correspond to any real server process running on any node.
  13. What is a Clone? - The copies of a server group are called Clones. But unlike a Server Group Clones are associated with a node and are real server process running in that node.
  14. What is Ripple Effect? - The process of propagating the changes in the properties of a server group during runtime to all the associated clones is called Ripple Effect.
  15. What level of Load Balancing is possible with EJBs? - The workload management service provides load balancing for the following types of enterprise beans: Homes of entity or session beans, Instances of entity beans, Instances of stateless session beans.
  16. What is the basic requirement for in-memory replication in Weblogic? - The data in session should consist only of Serialized objects. Only setAttribute function should be used to set objects in session.
  17. How JDBC services can be used in clustered environment? - Identical DataSource has to be created in each clustered server instances and configure to use different connection pools.
  18. What are the services that should not be used in a Clustered Environment? - Non-clustered services:
    1. File Services
    2. Time services
    3. Weblogic events
    4. Weblogic Workspaces (In WebLogic 5.1)
  19. Mention some tools to cluster Web Servers? - Web Servers can be clustered using Edge Server or DNS.
  20. What is in-memory replication? - The process by which the contents in the memory of one physical m/c are replicated in all the m/c in the cluster is called in-memory replication.
  21. Difference Between Abstraction and Encapsulation - Abstraction is removing some distinctions between objects, so as to show their commonalities. Encapsulation is hiding the details of the implementation of an object so that there are no external dependencies on the particular implementation.
                                            JMS Interview Questions

  1. What are the types of messaging? - There are two kinds of Messaging. Synchronous messaging involves a client that waits for the server to respond to a message. Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server.
  2. What is publish/subscribe messaging? - With publish/subscribe message passing the sending application/client establishes a named topic in the JMS broker/server and publishes messages to this queue. The receiving clients register (specifically, subscribe) via the broker to messages by topic; every subscriber to a topic receives each message published to that topic. There is a one-to-many relationship between the publishing client and the subscribing clients.
  3. Why doesn’t the JMS API provide end-to-end synchronous message delivery and notification of delivery? -Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API. JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can insure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer. The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.
  4. What are the core JMS-related objects required for each JMS-enabled application? - Each JMS-enabled client must establish the following:
    • A connection object provided by the JMS server (the message broker)
    • Within a connection, one or more sessions, which provide a context for message sending and receiving
    • Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
    • Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively). Within a session, a message object (to send or to receive)
  5. What is the Role of the JMS Provider? - The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.
  6. How does a typical client perform the communication? -
    1. Use JNDI to locate administrative objects.
    2. Locate a single ConnectionFactory object.
    3. Locate one or more Destination objects.
    4. Use the ConnectionFactory to create a JMS Connection.
    5. Use the Connection to create one or more Session(s).
    6. Use a Session and the Destinations to create the MessageProducers and MessageConsumers needed.
    7. Perform your communication.
  1. Give an example of using the point-to-point model. - The point-to-point model is used when the information is specific to a single client. For example, a client can send a message for a print out, and the server can send information back to this client after completion of the print job.
  2. How does the Application server handle the JMS Connection? -
    1. App server creates the server session and stores them in a pool.
    2. Connection consumer uses the server session to put messages in the session of the JMS.
    3. Server session is the one that spawns the JMS session.
    4. Applications written by Application programmers creates the message listener.

                                        J2EE Interview Questions

  1. What makes J2EE suitable for distributed multitiered Applications?
    - The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:
    • Client-tier components run on the client machine.
    • Web-tier components run on the J2EE server.
    • Business-tier components run on the J2EE server.
    • Enterprise information system (EIS)-tier software runs on the EIS server.
  2. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.
  3. What are the components of J2EE application?
    - A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
    1. Application clients and applets are client components.
    2. Java Servlet and JavaServer Pages technology components are web components.
    3. Enterprise JavaBeans components (enterprise beans) are business components.
    4. Resource adapter components provided by EIS and tool vendors.
  1. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logic
    that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.
  2. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.
  3. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
  4. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
  5. What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
  6. What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
  7. What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.
  8. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.
  9. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications.
    Enterprise beans and their container run on the J2EE server.
  10. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.
  11. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings.
  12. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.
  13. What are types of J2EE clients? - Following are the types of J2EE clients:
    • Applets
    • Application clients
    • Java Web Start-enabled rich clients, powered by Java Web Start technology.
    • Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
  1. What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations
    for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.
  2. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
  3. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
  4. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.
  5. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.
  6. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
  7. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and
    directory services such as LDAP, NDS, DNS, and NIS.
  8. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
  9. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.
                    Basic Servlets Questions
  1. What is the difference between CGI and Servlet?
  2. What is meant by a servlet?
  3. What are the types of servlets? What is the difference between 2 types of Servlets?
  4. What is the type of method for sending request from HTTP server ?
  5. What are the exceptions thrown by Servlets? Why?
  6. What is the life cycle of a servlet?
  7. What is meant by cookies? Why is Cookie used?
  8. What is HTTP Session?
  9. What is the difference between GET and POST methods?
  10. How can you run a Servlet Program?
  11. What is the middleware? What is the functionality of Webserver?
  12. What webserver is used for running the Servlets?
  13. How do you invoke a Servelt? What is the difference in between doPost and doGet methods?
  14. What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me their parameter names also?
  15. What are session variable in Servlets?
  16. What is meant by Session? Tell me something about HTTPSession Class?
  17. What is Session Tracking?
  18. Difference between doGet and doPost?
  19. What are the methods in HttpServlet?
  20. What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet?
                           Servlets Interview Question
  1. What is a servlet?
    Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.
  2. Whats the advantages using servlets over using CGI?
    Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.
  3. What are the general advantages and selling points of Servlets?
    A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online
    real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.
  4. Which package provides interfaces and classes for writing servlets? javax
  5. What’s the Servlet Interface?
    The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more
    commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet.
    The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.
  6. When a servlet accepts a call from a client, it receives two objects. What are they?
    ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.
  7. What information does ServletRequest allow access to?
    Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names
    of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods.
  8. What type of constraints can ServletResponse interface set on the client?
    It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through
    which the servlet can send the reply data.
  9. Explain servlet lifecycle?
    Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down.
  10. How does HTTP Servlet handle client requests?
    An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.
                                XJDBC Interview Question
  1. What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection.
  2. How can you load the drivers?
    Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code:
Class.forName("jdbc.DriverXYZ");
  1. What will Class.forName do while loading drivers? It is used to create an instance of a driver and register it with the
    DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
  2. How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS.
    The following line of code illustrates the general idea:
String url = “jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, “Fernanda", “J8?);
  1. How can you create JDBC statements and what are they?
    A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object
Statement stmt = con.createStatement();
  1. How can you retrieve data from the ResultSet?
    JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
String s = rs.getString("COF_NAME");
The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs.
  1. What are the different types of Statements?
    Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)
  2. How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a
    Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first.
  3. PreparedStatement updateSales =
  4. con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
  5. What does setAutoCommit do?
    When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.
con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
  1. How do you call a stored procedure from JDBC?
    The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open
    Connection object. A CallableStatement object contains a call to a stored procedure.
  2. CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
  3. ResultSet rs = cs.executeQuery();
  4. How do I retrieve warnings?
    SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an
    application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a
    Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these
    classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object:
  5. SQLWarning warning = stmt.getWarnings();
  6. if (warning != null)
  7. {
  8. System.out.println("n---Warning---n");
  9. while (warning != null)
  10. {
  11. System.out.println("Message: " + warning.getMessage());
  12. System.out.println("SQLState: " + warning.getSQLState());
  13. System.out.print("Vendor error code: ");
  14. System.out.println(warning.getErrorCode());
  15. System.out.println("");
  16. warning = warning.getNextWarning();
  17. }
  18. }
  19. How can you move the cursor in scrollable result sets?
    One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
  1. What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?
    You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:
  2. Statement stmt =
  3. con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
  4. ResultSet srs =
  5. stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
  6. srs.afterLast();
  7. while (srs.previous())
  8. {
  9. String name = srs.getString("COF_NAME");
  10. float price = srs.getFloat("PRICE");
  11. System.out.println(name + " " + price);
  12. }
  13. How to Make Updates to Updatable Result Sets?
    Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
  14. Connection con =
  15. DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
  16. Statement stmt =
  17. con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
  18. ResultSet uprs =
  19. stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");