Tuesday, April 27, 2010

SOA Interview Questions

Service Oriented architecture interview questions

What is the basic life cycle of a SOA composite application?

Use Oracle JDeveloper to design a SOA composite application with various SOA components.

Package the composite application for deployment.

Deploy the SOA composite application to the SOA Infrastructure. The SOA Infrastructure is a Java EE-compliant application running in Oracle WebLogic Server. The application manages composites and their life cycle, service engines, and binding components.

Use Oracle Enterprise Manager Fusion Middleware Control to monitor and manage the composite application for a farm's SOA infrastructure.

What is the Service Component Architecture (SCA) used for?

Service Component Architecture (SCA) assembly model abstracts the implementation and allows assembly of components, with little implementation details. SCA enables you to represent business logic as reusable service components that can be easily integrated into any SCA-compliant application. The resulting application is known as a SOA composite application. The specification for the SCA standard is maintained by the Organization for the Advancement of Structured Information Standards (OASIS).

What is the purpose of Service Data Objects (SDO)?

Service Data Objects (SDO) provides a data programming architecture. It provides a standardized view on data, and provides efficient transportation, as well as change capture, in form of a change summary. More specifically, it collects a data graph of related business objects, called DataObjects. This graph tracks the schema that describes the DataObjects. Knowledge is not required about how to access a particular back-end data source to use SDO in a SOA composite application. Consequently, you can use static or dynamic programming styles and obtain connected and disconnected access.

What is the purpose of Business Process Execution Language (BPEL)?

BPEL provides enterprises with an industry standard for business process orchestration and execution. Using BPEL, you design a business process that integrates a series of discrete services into an end-to-end process flow. This integration reduces process cost and complexity.

What is the purpose of XSL Transformations?

XSLT processes XML documents and transforms document data from one XML schema to another.

What is the purpose of Java Connector Architecture?

Java Connector Architecture JCA provides a Java technology solution to the problem of connectivity between the many application servers in Enterprise Information Systems (EIS).

What is the purpose of Java Messaging Service?

(JMS) provides a messaging standard that allows application components based on the Java Enterprise Edition (JEE) to access business logic distributed among heterogeneous systems.

What is the purpose of Web Service Description Language?

Web Service Description Language (WSDL) file provides a standardized view on the capabilities of a service. Bindings provide the entry points into the composite at runtime.

What is the purpose of SOAP over HTTP?

SOAP provides the default network protocol for message delivery.

What are the components comprise an Oracle SOA Suite installation?

The following components comprise an Oracle SOA Suite installation:

Service Infrastructure

Oracle Mediator

Oracle Adapters

Business Events and Events Delivery Network

Oracle Metadata Repository

Oracle Business Rules

Oracle WSM Policy Manager

Oracle BPEL Process Manager (Business Process Execution Language)

Human Workflow

Oracle Business Activity Monitoring

Oracle User Messaging Service

Oracle B2B

Oracle JDeveloper

Oracle Enterprise Manager

The following components are included with Oracle SOA Suite, but available as a separate download:

Oracle Service Bus (provides service virtualization and protocol transformations for oracle SOA appl)

Oracle Complex Event Processing

What is the purpose of Oracle Mediator?

Oracle mediator is used for route, validate, filter and transform data from service providers to external partners.

Route: Determines the service component (BPEL process, business rule, human task, and mediator) to which to send the messages.

Validate: Provides support for validating the incoming message payload by using a schematron or an XSD file.

Filter: If specified in the rules, applies a filter expression that specifies the contents (payload) of a message be analyzed before any service is invoked.

Transformation: If specified in the rules, transforms document data from one XML schema to another, thus enabling data interchange among applications using different schemas.

What is the purpose of Oracle Service Bus?

Oracle Service Bus provides standalone service bus capabilities, enabling separation between application developers and target systems or services. Oracle Service Bus receives messages through a transport protocol such as HTTP(S), JMS, File, and

FTP, and sends messages through the same or a different transport protocol. Service response messages follow the inverse path. Oracle Service Bus handles the deployment, management, mediation, messaging, security and governance of implementing SOA to enterprise applications.

What is the purpose of Oracle Adapters?

Oracle Adapters use JCA (Java Connector Architecture) technology to connect external systems to the Oracle SOA Suite. Oracle SOA Suite provides the following technology adapters to integrate with transport protocols, data stores, and messaging middleware:

BAM

FTP

Java Messaging Service (JMS)

Advanced Queuing (AQ)

Files

Message Queuing (MQ) Series

Legacy Adapters

Application Adapters

What is the purpose of Business events?

Business events are messages sent as the result of an occurrence or situation, such as a new order or completion of an order. In Oracle SOA Suite, the mediator service component subscribes or publishes events. When an event is published, other applications can subscribe to it.

What is Oracle Metadata Repository ?

Oracle Metadata Repository MDS stores business events, rulesets for use by Oracle Business Rules, XSLT files for Oracle Service Bus and Oracle Mediator, XSD XML schema files for Oracle BPEL Process Manager, WSDL files, and metadata files for Complex Event Processing.

What is Oracle Business rules used for?

Oracle Business Rules, initiated by a BPEL process service component, enable dynamic decisions at runtime. In addition, the human task and mediator service components can make use of rules for dynamic routing.

What is the purpose of Oracle WSM Policy Manager?

Oracle WSM Policy Manager provides the infrastructure for enforcing global security and auditing policies in the Service Infrastructure.

What is the purpose of Oracle BPEL Process Manager?

Oracle BPEL Process Manager enables you to orchestrate synchronous and asynchronous services into end-to-end BPEL process flows. You also integrate technology adapters and services, such as human tasks, transformations, notifications, and business rules within the process.

Oracle Business Activity Monitoring (Oracle BAM) is a complete solution for building real-time operational dashboards and monitoring and alerting applications over the Web. Oracle SOA Suite makes it easy to expose SOA events, such as BPEL processes, to the BAM engine.

Oracle Complex Event Processing (Oracle CEP), a data management infrastructure that supports the notion of streams of structured data records together with stored relations. Oracle CEP is included with Oracle SOA Suite, but available as a separate download. It is optimized to handle very large volumes of events, such as those found in bank transactions, that cannot be managed by Oracle BAM. In addition, Oracle Complex Event Processing can perform complex correlations and pattern matching.

Oracle B2B is an eCommerce gateway that enables the secure and reliable exchange of messages between an enterprise and its trading partners.

COM application initiates the purchase order.

A mediator service component receives the purchase order. It validates, performs code conversion, transforms the purchase order to a canonical, and routes the document. (Canonical refers to a canonical data model that is used to transition between different document standards.)

A BPEL process service component receives the purchase order, orchestrates any required business process, and can invoke a human task, business rule, and error handling as required.

A mediator service component receives the purchase order, validates, performs code conversion, transforms the canonical to the target purchase order, and routes the document.

B2B receives the purchase order, identifies the partner, identifies the agreement, validates the purchase order, translates the purchase order to EDI, generates the EDI envelope, generates acknowledgments, and manages the secure exchange of the purchase order with the external trading partner.

Oracle JDeveloper is the development component of Oracle SOA Suite. It forms a comprehensive Integrated Service Environment (ISE) for creating and deploying composite applications and managing the composite. Oracle JDeveloper enables developers to model, create, discover, assemble, orchestrate, test, deploy, and maintain composite applications based on services.

The SOA Composite Editor enables you to create, edit, and deploy services, and also to assemble them in a composite application, all from a single location. These components are integrated together into one application and communicate with the outside world through binding components such as Web services and JCA adapters.

The SOA Composite Editor enables you to use either of two approaches for designing SOA composite applications:

The top-down approach of building a composite application puts interfaces first and implementation next. For example, you first add BPEL processes, human tasks, business rules, and Oracle Mediator routing services components to an application, and later define the specific content of these service components.

The bottom-up approach takes existing implementations of service components and wraps them with Web service interfaces for assembly into a composite application. For example, you first create and define the specific content of BPEL processes, human tasks, business rules, and Oracle Mediator routing services components, and later create a SOA composite application to which you add these service components.

Additional editors provided by J editor

Oracle BPEL Designer: You can create a BPEL process service component in the SOA composite application of Oracle JDeveloper and then design it by using the BPEL Designer, which is displayed, when you double-click a BPEL process in the SOA Composite Editor.

Oracle Mediator Editor: You can create a mediator service component in the SOA composite application of Oracle JDeveloper, and then design it by using the Mediator Editor, which is displayed when you double-click a Mediator in SOA Composite Editor.

Human Task Editor: You can create a human task service component in the SOA composite application of Oracle JDeveloper and then design it by using the Human Task Editor, which is displayed when you double-click a human task in the SOA Composite Editor.

Business Rules Designer: You can create a business rules service component in the SOA composite application of Oracle JDeveloper and then design it by using the Business Rules Designer, which is displayed when you double-click a business rule in the SOA Composite Editor.

Oracle Enterprise Manager

You can configure, monitor, and manage your SOA composite application during run time from Oracle Enterprise Manager Fusion Middleware Control Console. Fusion Middleware Control is a Web browser-based, graphical user interface that you can use to monitor and administer a farm.

A farm is a collection of components managed by Fusion Middleware Control. It contains Oracle WebLogic Server domains, one Administration Server, one or more Managed Servers, clusters, and the Oracle Fusion Middleware components that are installed, configured, and running in the domain.

You deploy SOA composite applications designed in Oracle JDeveloper to the SOA Infrastructure. The SOA Infrastructure is a Java EE-compliant application running in Oracle WebLogic Server. The application manages composites and their life cycle, service engines, and binding components.

The SOA Infrastructure provides you with access to all deployed SOA composite applications, service engines, service components, business events, and other elements. Fusion Middleware Control organizes a wide variety of performance data and administrative functions into distinct, Web-based home pages for the farm, domain, servers, components, and applications.

Fusion Middleware Control provides a wide variety of administrative and performance data for the SOA components, composite applications, and composite instances within the SOA infrastructure, enabling you to administer and pinpoint issues.

The basic life cycle of a SOA composite application is as follows:

Use Oracle JDeveloper to design a SOA composite application with various SOA components.

Package the composite application for deployment.

Deploy the SOA composite application to the SOA Infrastructure. The SOA Infrastructure is a Java EE-compliant application running in Oracle WebLogic Server. The application manages composites and their life cycle, service engines, and binding components.

Use Oracle Enterprise Manager Fusion Middleware Control to monitor and manage the composite application for a farm's SOA infrastructure.

Services provide the outside world with an entry point to the SOA composite application. The WSDL file of the service advertises its capabilities to external applications. These capabilities are used for contacting the SOA composite application components. The binding connectivity of the service describes the protocols that can communicate with the service, for example, SOAP/HTTP or a JCA adapter.

Software tester (SQA) interview questions

The project had a very high cost of testing. After going in detail, someone found out that the testers are spending their time on software that doesn’t have too many defects. How will you make sure that this is correct?

What are the disadvantages of overtesting?

What happens to the test plan if the application has a functionality not mentioned in the requirements?

You are given two scenarios to test. Scenario 1 has only one terminal for entry and processing whereas scenario 2 has several terminals where the data input can be made. Assuming that the processing work is the same, what would be the specific tests that you would perform in Scenario 2, which you would not carry on Scenario 1?

Your customer does not have experience in writing Acceptance Test Plan. How will you do that in coordination with customer? What will be the contents of Acceptance Test Plan?

How do you know when to stop testing?

What can you do if the requirements are changing continuously?

What is the need for Test Planning?

What are the various status reports you will generate to Developers and Senior Management?

Define and explain any three aspects of code review?

Why do you need test planning?

Explain 5 risks in an e-commerce project. Identify the personnel that must be involved in the risk analysis of a project and describe their duties.. How will you prioritize the risks?

What are the various status reports that you need generate for Developers and Senior Management?

You have been asked to design a Defect Tracking system. Think about the fields you would specify in the defect tracking system?

Write a sample Test Policy?

Explain the various types of testing after arranging them in a chronological order?

Explain what test tools you will need for client-server testing and why?

Explain what test tools you will need for Web app testing and why?

Explain pros and cons of testing done development team and testing by an independent

team?

Explain Stress, Load and Performance testing?

Describe automated capture/playback tools and list their benefits?

How can software QA processes be implemented without stifling productivity?

How is testing affected by object-oriented designs?

What is extreme programming and what does it have to do with testing?

Write a test transaction for a scenario where 6.2% of tax deduction for the first $62,000 of income has to be done?

What would be the Test Objective for Unit Testing? What are the quality measurements to assure that unit testing is complete?

Prepare a checklist for the developers on Unit Testing before the application comes to testing department.

Draw a pictorial diagram of a report you would create for developers to determine project status.

Draw a pictorial diagram of a report you would create for users and management to determine project status.

What 3 tools would you purchase for your company for use in testing? Justify the need?

Put the following concepts, put them in order, and provide a brief description of each:

system testing

acceptance testing

unit testing

integration testing

benefits realization testing

What are two primary goals of testing?

If your company is going to conduct a review meeting, who should be on the review committe and why?

Write any three attributes which will impact the Testing Process?

What activity is done in Acceptance Testing, which is not done in System testing?

You are a tester for testing a large system. The system data model is very large with many attributes and there are a lot of inter-dependencies within the fields. What steps would you use to test the system and also what are the effects of the steps you have taken on the test plan?

Explain and provide examples for the following black box techniques?

Boundary Value testing

Equivalence testing

Error Guessing

What are the product standards for?

Test Plan

Test Script and Test Report

You are the test manager starting on system testing. The development team says that due to a change in the requirements, they will be able to deliver the system for SQA 5 days past the deadline. You cannot change the resources (work hours, days, or test tools).

What steps will you take to be able to finish the testing in time?

Your company is about to roll out an e-commerce application. It’s not possible to test the application on all types of browsers on all platforms and operating systems. What steps would you take in the testing environment to reduce the business risks and commercial risks?

In your organization, testers are delivering code for system testing without performing unit testing. Give an example of test policy:

Policy statement

Methodology

Measurement

Testers in your organization are performing tests on the deliverables even after significant defects have been found. This has resulted in unnecessary testing of little value, because re-testing needs to be done after defects have been rectified. You are going to update the test plan with recommendations on when to halt testing. Wwhat recommendations are you going to make?

How do you measure:

Test Effectiveness

Test Efficiency

You found out the senior testers are making more mistakes then junior testers; you need to communicate this aspect to the senior tester. Also, you don’t want to lose this tester.

How should one go about constructive criticism?

You are assigned to be the test lead for a new program that will automate take-offs and landings at an airport. How would you write a test strategy for this new program?

What is a QTP action? - An action is a QTP script used for testing a particular segment of the application. Actions help in dividing the tests into logical units.

reusable and non-reusable actions.

What is QTP Flow? - Each reusable action will be called sequentially from a separate script. This script which calls all the actions pertaining to the business functionality sequentially is called a “Flow”.

What is Data Table used for in QTP? - Data Table is an excel table which holds the data to be entered into the applications to test the various conditions of business functionality.

It consists of all Global and Local Data sheets. E.G. GlobalDataTable.xls is called the Data Table.

Data Sheet - It is one of the sheets in the Data Table. E.G.,Global Data Sheet and ClientData, VendorData etc.

What is an Object Repository used for in QTP?- Object Repository (OR) is a collection of objects pertaining to the application under test. E.G All the text boxes, list boxes, images etc are stored in a file in QTP. This file is called the object repository. Each object will have the set of properties to identify that object uniquely in the application.

What is a Function Library used in QTP? - Function is a QTP script wrapped into a VBScript. When we have a set of lines in QTP script, which have to be executed multiple times in the same script or in different scripts, we wrap them into a function and give them a name which would be a function name. Function library is a set of such functions created for the entire project. For a project we may need functions like Login, Logoff and, CloseAllBrowsers etc. These functions should be written in a text file and then saved as a VB Script file (.vbs extension).

What is QTP Initialization Script ? - Initialization script is an action which grabs the required variables and defines any environment variables required. This should be the first action in the flow of actions.

What is an Environment Variable? - Environment variables are the variables which can be defined and made available to the entire flow of actions or for just one action.

What is difference between built in and user defined QTP?

Built-in: These are predefined by QTP. E.G. ActionIteration, OSVersion etc. The values of the Built-in environment variables can not be changed.

User-Defined: These are defined by the user as and when required.

What are the Steps for Creation of Flow in QTP?

1. When inserting a reusable action into the flow, always use the option “Call to Existing Action” and not the “Call to Copy of Action”. This way, the called action will be read only. Any changes we need to make in the called actions should be made by opening that action. These changes are automatically applied in the flow as well.

2. When inserting a reusable action into the flow make sure that all the actions are inserted at the same hierarchy. When inserting the reusable action from the keyword view place your cursor on the Action1 which is the flow action then select the radio button “After the Current Step”. Make sure your cursor is placed on the Action1 everytime you insert an action. Later you can move the reusable actions into the order you want them to be executed.

3. “Call to Copy of Action” may be used in some situations where you want to use the code of the reusable action but need to make some changes to the code in order to accomplish a task. The updates made to the original action will not be updated in the flow with this option.

4. Most of the times there are test cases which are almost similar in flow of data except that the data changes according to the change in the test scenario. Such test cases have to be grouped together and the data for these test cases should be put in the Global Sheet of the data table in separate rows. This way each row of the global sheet of the data table represents one test case.

5. Local table in most cases is used if the data is confined to a particular reusable action only or if a particular portion of the reusable action has to be repeated with multiple data say for example within a customer account you are creating locations for that customer that has 10 locations. In this case the location data has to be placed in the local sheet for that reusable action.

6. Local table of each reusable action should be editable from the flow. The data entered from the flow into this local sheet is not updated in the original action. This way the reusable action can be best used if you want to call the same reusable action into a different flow. The data is tied to the flow not to the action. To do this, after inserting the action, right click on the action in the Keyword view to go to action properties of the external/reusable action and in the External Action tab’s Data Table Parameters section, select the radio button “Use a local, editable copy”.

What are the guidelines for Object Repository Management

1. There should be one Object Repository per application/project. This makes it easy for automation engineer to change the object descriptions or add/delete objects when changes are made to the application.

2. There might be a situation where the Object Repository (OR) grows very large and QTP might fail in saving the new objects to the OR. This is a known issue and Mercury Interactive has released a patch for addressing this issue which can be downloaded from the support site or going to “check for updates” in the The patch number is 1129. Not required for QTP 9.

3. The downside of having the large repository is that the test flow may take longer to launch.

4. All the actions and flow should be using the same shared OR. This will ensure that the objects recorded for the entire application will be at one place.

5. Always schedule daily backup copy of the Object Repository on your local hard drive. There are instances where the OR gets corrupted.

Structs Interview Questions and Answers

What is Struts?

Struts is a web page development framework and an open source software that helps developers build web applications quickly and easily. 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.

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.

Who makes the Struts?

Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project, like Tomcat, Ant and Velocity.

Why it called Struts?

Because the designers want to remind us of the invisible underpinnings that hold up our houses, buildings, bridges, and ourselves when we are on stilts. This excellent description of Struts reflect the role the Struts plays in developing web applications.

Do we need to pay the Struts if being used in commercial purpose?

No. Struts is available for commercial use at no charge under the Apache Software License. You can also integrate the Struts components into your own framework just as if they were written in house without any red tape, fees, or other hassles.

What are the core classes of Struts?

Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.

What is the design role played by Struts?

The role played by Structs is controller in Model/View/Controll er(MVC) style. The View is played by JSP and Model is played by JDBC or generic data source classes. The Struts controller is a set of programmable components that allow developers to define exactly how the application interacts with the user.

How Struts control data flow?

Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keep control-flow decisions out of presentation layer.

What configuration files are used in Struts?

ApplicationResource s.properties

struts-config. xml

These two files are used to bridge the gap between the Controller and the Model.

What helpers in the form of JSP pages are provided in Struts framework?

--struts-html. tld

--struts-bean. tld

--struts-logic. tld

Is Struts efficient?

The Struts is not only thread-safe but thread-dependent( instantiates each Action once and allows other requests to be threaded through the original object.

ActionForm beans minimize subclass code and shorten subclass hierarchies

The Struts tag libraries provide general-purpose functionality

The Struts components are reusable by the application

The Struts localization strategies reduce the need for redundant JSPs

The Struts is designed with an open architecture- -subclass available

The Struts is lightweight (5 core packages, 5 tag libraries)

The Struts is open source and well documented (code to be examined easily)

The Struts is model neutral

How you will enable front-end validation based on the xml in validation.xml?

The <> tag to allow front-end validation based on the xml in validation.xml. For example the code: < formname="logonForm" dynamicjavascript=" true" staticjavascript=" true"> generates the client side java script for the form logonForm as defined in the validation.xml file. The <> when added in the jsp file generates the client site validation script.

What is ActionServlet?

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

How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config. xml file through <> tag. Example: < parameter=" MessageResources">

Structs Interview Questions and Answers

What is Struts?

Struts is a web page development framework and an open source software that helps developers build web applications quickly and easily. 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.

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.

Who makes the Struts?

Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project, like Tomcat, Ant and Velocity.

Why it called Struts?

Because the designers want to remind us of the invisible underpinnings that hold up our houses, buildings, bridges, and ourselves when we are on stilts. This excellent description of Struts reflect the role the Struts plays in developing web applications.

Do we need to pay the Struts if being used in commercial purpose?

No. Struts is available for commercial use at no charge under the Apache Software License. You can also integrate the Struts components into your own framework just as if they were written in house without any red tape, fees, or other hassles.

What are the core classes of Struts?

Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.

What is the design role played by Struts?

The role played by Structs is controller in Model/View/Controll er(MVC) style. The View is played by JSP and Model is played by JDBC or generic data source classes. The Struts controller is a set of programmable components that allow developers to define exactly how the application interacts with the user.

How Struts control data flow?

Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keep control-flow decisions out of presentation layer.

What configuration files are used in Struts?

ApplicationResource s.properties

struts-config. xml

These two files are used to bridge the gap between the Controller and the Model.

What helpers in the form of JSP pages are provided in Struts framework?

--struts-html. tld

--struts-bean. tld

--struts-logic. tld

Is Struts efficient?

The Struts is not only thread-safe but thread-dependent( instantiates each Action once and allows other requests to be threaded through the original object.

ActionForm beans minimize subclass code and shorten subclass hierarchies

The Struts tag libraries provide general-purpose functionality

The Struts components are reusable by the application

The Struts localization strategies reduce the need for redundant JSPs

The Struts is designed with an open architecture- -subclass available

The Struts is lightweight (5 core packages, 5 tag libraries)

The Struts is open source and well documented (code to be examined easily)

The Struts is model neutral

How you will enable front-end validation based on the xml in validation.xml?

The <> tag to allow front-end validation based on the xml in validation.xml. For example the code: < formname="logonForm" dynamicjavascript=" true" staticjavascript=" true"> generates the client side java script for the form logonForm as defined in the validation.xml file. The <> when added in the jsp file generates the client site validation script.

What is ActionServlet?

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

How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config. xml file through <> tag. Example: < parameter=" MessageResources">

Why is it called Struts?

It's a reference to struts in the architectural sense, a reminder of the nearly invisible pieces that hold up buildings, houses, and bridges.

Do I have to credit Struts on my own website?

You need to credit Struts if you redistribute your own framework based on Struts for other people to use. (See the Apache License for details.) But you do not need to credit Struts just because your web application utilizes the framework. It's the same situation as using the Apache HTTPD server or Tomcat. Not required if its just running your web site.

Where can I get a copy of Struts?

The best place to download Struts is at struts.apache. org. The nightly builds are very stable, and recommended as the best place to start today.

How do I install Struts?

To develop applications with Struts, you can usually just add the Struts JAR file to your Java development environment. You can then start using the Struts classes as part of your own application. A blank Struts application (in the webapps directory, open struts-blank. war) is provided, which you can just copy to get a quick-start on your own brainchild.

Since the full source code for Struts is available, we also provide complete instructions for compiling your own Struts JAR from scratch. (This is actually easier than it looks!)

Your Struts application can usually be deployed using a standard WAR file. In most cases, you simply deposit the WAR file on your application server, and it is installed automatically. If not, step-by-step installation instructions for various servlet containers are available.

When do I need "struts.jar" on my classpath?

When you are compiling an application that uses the Struts classes, you must have the "struts.jar" on the classpath your compiler sees -- it does not have to be on your CLASSPATH environment variable.

Why is that an important distinction? Because if you are using a servlet container on your development machine to test your application, the "struts.jar" must not be on your CLASSPATH environment variable when running the container. (This is because each Web application must also have their own copy of the Struts classes, and the container will become confused if it is on the environment path as well.)

There are several general approaches to this issue:

* Use ANT for building your projects -- it can easily assemble classpaths for the compiler. (This is how Struts itself is built, along with Tomcat and most other Java-based projects).

* Use an IDE where you can configure the "class path" used for compilation independent of the CLASSPATH environment variable.

* Use a shell script that temporarily adds struts.jar to the classpath just for compilation, for example javac -classpath /path/to/struts. jar:$CLASSPATH $@

Does Struts include its own unit tests?

Struts currently has two testing environments, to reflect the fact that some things can be tested statically, and some really need to be done in the environment of a running servlet container.

For static unit tests, we use the JUnit framework. The sources for these tests are in the "src/test" hierarchy in the source repository, and are executed via the "test.junit" target in the top-level build.xml file. Such tests are focused on the low-level functionality of individual methods, are particularly suitable for the static methods in the org.apache.struts. util utility classes. In the test hierarchy, there are also some "mock object" classes (in the org.apache.struts. mock package) so that you can package up things that look like servlet API and Struts API objects to pass in as arguments to such tests.

Another valuable tool is Struts TestCase which provides a useful harness for Action classes that can be used with JUnit or Cactus.

If the framework doesn't do what I want, can I request that a feature be added?

First, it's important to remember that Struts is an all-volunteer project. We don't charge anyone anything to use Struts. Committers and other developers work on Struts because they need to use it with their own applications. If others can use it too, that's "icing on the cake". If you submit a patch for a feature that a Committer finds useful, then that Committer may choose to volunteer his or her time to apply the patch. If you just submit an idea without a patch, it is much less likely to be added (since first someone else has to volunteer their time to write the patch).

We are grateful for any patches, and we welcome new ideas, but the best way to see that something gets added to the framework is to do as much of the work as you can, rather than rely on the "kindness of strangers". Worst case, you can apply the patch to your copy of Struts and still use the feature in your own application. (Which is what open source is ~really~ all about.)

Where can I get help with Struts?

The Struts package comes complete with a Users Guide to introduce people to the framework and its underlying technologies. Various components also have their own in-depth Developers Guide, to cover more advanced topics. Comprehensive Javadocs are included along with the full source code. For your convenience, these are bundled together as a self-installing application. The struts-documentatio n.war is the same bundle that is deployed as the Struts Web site.

The Strut's mailing list is also very active, and welcomes posts from new users. Before posting a new question, be sure to consult the MAILING LIST ARCHIVE and the very excellent How To Ask Questions The Smart Way by Eric Raymond. Please do be sure to turn off HTML in your email client before posting.

What's the difference between Struts and Turbine? What's the difference between Struts and Espresso?

If you are starting from scratch, packages like Turbine and Espresso can be very helpful since they try to provide all of the basic services that your team is likely to need. Such services include things like data persistence and logging.

If you are not starting from scratch, and need to hook up your web application to an existing infrastructure, then "plain vanilla" Struts can be a better choice. The core Struts framework does not presuppose that you are using a given set of data persistence, presentation, or logging tools. Anything goes =:0)

Compared to other offerings, Struts endeavors to be a minimalist framework. We try leverage existing technologies whenever we can and provide only the missing pieces you need to combine disparate technologies into a coherent application. This is great when you want to select your own tools to use with Struts. But, if you prefer a more integrated infrastructure, then packages like Turbine or Espresso (which uses Struts) are perfectly good ways to go.

See also

* <>

* <>

* <>

Why aren't the Struts tags maintained as part of the Jakarta Taglibs project ?

Development of both products began about the same time. Leading up to the release of 1.0, it was thought better to continue to develop the taglibs alongside the controller. Now that 1.0 is out, the JavaServer Pages Standard Taglib is in active development. Once work on JSTL stabilizes, the Struts taglibs will be revisited. Tags which are not linked directly to the framework may be hosted at Jakarta Taglibs instead.

Are the Struts tags XHTML compliant ?

If you use an or element on your page, the tags will render as XHTML (since Struts 1.1).

Will the Struts tags support other markup languages such as WML ?

Struts itself is markup neutral. The original Struts taglibs are only one example of how presentation layer components can access the framework. The framework objects are exposed through the standard application, session, and request contexts, where any Java component in the application can make use of them.

Markup extensions that use Struts are available for Velocity and XLST, among others. A new Struts tag library for Java Server Faces is also in development.

For more about using WAP/WML with Struts see the article WAP up your EAserver.

What about JSTL and JavaServer Faces ?

JSTL, the JavaServer Standard Tag Library, is a set of JSP tags that are designed to make it easier to develop Web applications. JavaServer Faces (JSF) is a specification for a new technology that promises to make it easier to write MVC applications, both for the Web and for the desktop.

The inventor of Struts, Craig McClanahan, is the specification co-lead for JavaServer Faces (JSR 127), and architect of the reference implemenation as well as Java Studio Creator. Both JSTL and JSF are complementary to Struts.

The mainstay of the Struts framework is the controller components, which can be used with any Java presentation technology. As new technologies become available, it is certain that new "glue" components will also appear to help these technologies work as well with Struts.

Struts originally came bundled with a set of custom JSP tags. Today, several extensions are available to help you use Struts with other popular presentation technologies, like XSLT and Velocity. Likewise, extensions for JSTL and JSF are now available as well.

The JSTL reference implementation is available through the Jakarta Taglibs site. A JSTL taglibs for Struts, Struts-El , is available and distributed with Struts beginning with the 1.1 release.

The JSF specification and reference implementation is available through Sun's The JSF specification and reference implementation is available through Sun's Java ServerFaces page. An early-release JavaServer Faces taglib for Struts, Struts-Faces, is also in early release and available through the nightly build. The Struts Faces taglib is expected to work with any compliant JSF implementation, including MyFaces.

Is there a particularly good IDE to use with Struts

Struts should work well with any development environment that you would like to use, as well as with any programmers editor. The members of the Struts development team each use their own tools such as Emacs, IDEA, Eclipse, and NetBeans.

Why was reload removed from Struts (since 1.1)?

The problem with ReloadAction was that Struts was trying to act like a container, but it couldn't do a proper job of it. For example, you can't reload classes that have been modified, or (portably) add new classes to a running web application (even if the container supported it).

Meanwhile, as Struts 1.1 was being developed, work progressed on things like Tomcat's reload command via the Manager webapp. This feature allows you to quickly reload-on-demand, complete with saving and restoring your session). It started to make even less sense for Struts to half-implement a feature that containers are implementing fully.

A more minor point is that freezing the configuration information at application startup time allows Struts to safely access the mapping information without bothering with synchronization. The "startup-only" strategy creates a modest but real improvement in performance for all users.

So, ReloadAction is not supported since Struts 1.1 for two reasons:

* It never did let you reload everything that you would really want to -- particularly changed classes -- so many people ended up having to reload the webapp anyway.

* Containers are starting to offer reload-on-demand features which does the same thing as the Struts ReloadAction, only better.

* Not supporting ReloadAction lets Struts avoid doing synchronization locks around all the lookups (like figuring out which action to use, or the destination of an ActionForward) so applications can run a little faster.

Of course, if someone came up with an implementation that solved these problems without creating any others, we would not be opposed to including a new ReloadAction.

What is a modular application? What does module-relative mean?

Since Struts 1.1, the framework supports multiple application modules. All applications have at least one root, or default, module. Like the root directory in a file system, the default application has no name. (Or is named with an empty string, depending your viewpoint.) Developing an application with only a default module is no different from how applications were developed under Struts 1.0. Since Struts 1.1, you can add additional modules to your application, each of which can have their own configuration files, messages resources, and so forth. Each module is developed in the same way as the default module. Applications that were developed as a single module can added to a multiple module application, and modules can promoted to a standalone application without change. For more about configuring your application to support multiple modules, see Configuring Applications in the User Guide.

But to answer the question =:0), a modular application is a Struts application that uses more than one module. Module-relative means that the URI starts at the module level, rather than at the context level, or the absolute-URL level.

* Absolute URL: http://localhost/ myApplication/ myModule/ myAction. do

* context-relative: /myModule/myAction. do

* module-relative: /myAction.do

The Struts Examples application is a modular application that was assembled from several applications that were created independently.

Why are some of the class and element names counter-intuitive?

The framework grew in the telling and, as it evolved, some of the names drifted.

The good thing about a nightly build, is that everything becomes available to the community as soon as it is written. The bad thing about a nightly build is that things like class names get locked down early and then become difficult to change.

Why is ActionForm a base class rather than an interface?

The MVC design pattern is very simple to understand but much more difficult to live with. You just need this little bit of Business Logic in the View logic or you need just that little bit of View logic in the Business tier and pretty soon you have a real mess.

Making ActionForm a class takes advantage of the single inheritance restriction of Java to it makes it more difficult for people to do things that they should not do.

ActionForms implemented as interfaces encourage making the property types match the underlying business tier instead of Strings, which violates one of the primary purposes for ActionForms in the first place (the ability to reproduce invalid input, which is a fundamental user expectation) . ActionForms as an interface would also encourage using existing DAO objects as ActionForms by adding ‘implements ActionForm’ to the class. This violates the MVC design pattern goal of separation of the view and business logic.

Since the goal of struts is to enforce this separation, it just makes more sense for Struts to own the ActionForm.

DynaActionForms relieve developers of maintaining simple ActionForms. For near zero maintenance, try Niall Pemberton's LazyActionForm

Do ActionForms have to be true JavaBeans?

The utilities that Struts uses (Commons-BeanUtils since 1.1) require that ActionForm properties follow the JavaBean patterns for mutators and accessors (get*,set*,is* ). Since Struts uses the Introspection API with the ActionForms, some containers may require that all the JavaBean patterns be followed, including declaring "implements Serializable" for each subclass. The safest thing is to review the JavaBean specification and follow all the prescribed patterns.

Since Struts 1.1, you can also use DynaActionForms and mapped-backed forms, which are not true JavaBeans. For more see ActionForm classes in the User Guide and Using Hashmaps with ActionForms in this FAQ.

Can I use multiple HTML form elements with the same name?

Yes. Define the element as an array and Struts will autopopulate it like any other.

private String[] id= {};

public String[] getId() { return this.id; }

public void setItem(String id[]) {this.id = id;}

And so forth

Can I use multiple HTML form elements with the same name?

Yes. The issue is that only one action class can be associated with a single form. So the real issue is how do I decode multiple submit types to a single Action class. There is more than one way to achieve this functionality.

The way that is suggested by struts is right out of the javadoc for LookupDispatchActio n . Basically, LookupDispatchActio n is using the keys from ApplicationProperti es.resources as keys to a map of actions available to your Action class. It uses reflection to decode the request and invoke the proper action. It also takes advantage of the struts tags and is straight forward to implement.

You can roll your own with JavaScript events and javascript:void (document.forms[ "myform"] .submit) on any html element. This gives you control of how you want your page to look. Again you will have to decode the expected action in the execute method of your action form if you choose this route.

Why doesn't the focus feature on the tag work in every circumstance?

Unfortunately, there is some disagreement between the various browsers, and different versions of the same browser, as to how the focus can be set. The tag provides a quick and easy JavaScript that will set the focus on a form for most versions of most browsers. If this feature doesn't work for you, then you should set the focus using your own JavaScript. The focus feature is a convenient "value-add" -- not a core requirement of the tag. If you do come up with a JavaScript that provides the final solution to this project, please post your patch to this Bugzilla ticket.

Why are my checkboxes not being set from ON to OFF?

A problem with a checkbox is that the browser will only include it in the request when it is checked. If it is not checked, the HTML specification suggests that it not be sent (i.e. omitted from the request). If the value of the checkbox is being persisted, either in a session bean or in the model, a checked box can never unchecked by a HTML form -- because the form can never send a signal to uncheck the box. The application must somehow ascertain that since the element was not sent that the corresponding value is unchecked.

The recommended approach for Struts applications is to use the reset method in the ActionForm to set all properties represented by checkboxes to null or false. The checked boxes submitted by the form will then set those properties to true. The omitted properties will remain false. Another solution is to use radio buttons instead, which always submit a value.

It is important to note that the HTML specification recommends this same behavior whenever a control is not "successful" . Any blank element in a HTML form is not guaranteed to submitted. It is therefor very important to set the default values for an ActionForm correctly, and to implement the reset method when the ActionForm might kept in session scope.

Can't I just create some of my JavaBeans in the JSP using a scriptlet?

Struts is designed to encourage a Model 2/MVC architecture. But there is nothing that prevents you from using Model 1 techniques in your JavaServer Pages, so the answer to the question is "Yes, you can".

Though, using Model 1 techniques in a Struts application does go against the grain. The approach recommended by most Struts developers is to create and populate whatever objects the view may need in the Action, and then forward these through the request. Some objects may also be created and stored in the session or context, depending on how they are used.

Likewise, there is nothing to prevent you from using scriptlets along with JSP tags in your pages. Though, many Struts developers report writing very complex scriplet-free applications and recommend the JSP tag approach to others.

For help with Model 1 techniques and scriptlets, you might consider joining the Javasoft JSP-interest mailing list, where there are more people still using these approaches.

Can I use JavaScript to submit a form?

You can submit a form with a link as below. BTW, the examples below assume you are in an block and 'myForm' is picked up from the struts-config. xml name field of the action.

My Link

Now the trick in the action is to decode what action you intend to perform. Since you are using JavaScript, you could set a field value and look for it in the request or in the form.

... html/javascript part ...

onclick='document. forms["myForm" ].myAction. value="save" ;

document.forms[ "myForm"] .submit() ;' />

onclick='document. forms["myForm" ].myAction. value="delete" ;

document.forms[ "myForm"] .submit() ;' />

... the java part ...

class MyAction extends ActionForm implements Serializable {

public ActionForward execute (ActionMapping map, ActionForm form,

HttpServletRequest req, HttpServletResponse ) {

String myAction = req.getParameter( "myAction" );

if (myAction.equals( "save") {

// ... save action ...

} else if (myAction.equals( "delete") {

// ... delete action ...

}

}

}

}

This is just one of many ways to achieve submitting a form and decoding the intended action. Once you get used to the framework you will find other ways that make more sense for your coding style and requirements. Just remember this example is completely non-functional without JavaScript.

How do I use JavaScript to ...

Struts is mainly a server-side technology. We bundled in some JSP tags to expose the framework components to your presentation page, but past that, the usual development process applies.

Interactive pages require the use of JavaScript. (That's why it was invented.) If you want things popping up or doing this when they click that, you are outside the scope of Struts and back into the web development mainstream.

You use JavaScript with Struts the same way you use with any presentation page. Since JavaScript is a client-side technology, you can use simple relative references to your scripts. If you need to fire a JavaScript from a HTML control, the Struts HTML tags have properties for the JavaScript events.

A very good JavaScript resource is Matt Kruse's site at http://www.mattkrus e.com/javascript / Do I need to implement reset and set all my form properties to their initial values?

No. You need to set checkbox properties to false if the ActionForm is being retained in session scope. This is because an unchecked box does not submit an attribute. Only checked boxes submit attributes. If the form is in session scope, and the checkbox was checked, there is no way to turn it back off without the reset method. Resetting the properties for other controls, or for a request scope form, is pointless. If the form is in request scope, everything already just started at the initial value.

Can I use other beans or hashmaps with ActionForms?

Yes. There are several ways that you can use other beans or hashmaps with ActionForms.

* ActionForms can have other beansor hashmaps as properties

* "Value Beans" or "Data Transfer Objects" (DTOs) can be used independently of ActionForms to transfer data to the view

* ActionForms can use Maps to support "dynamic" properties (since Struts 1.1)

ActionForms (a.k.a. "form beans") are really just Java beans (with a few special methods) that Struts creates and puts into session or request scope for you. There is nothing preventing you from using other beans, or including them in your form beans. Here are some examples:

Collections as properties Suppose that you need to display a pulldown list of available colors on an input form in your application. You can include a string-valued colorSelected property in your ActionForm to represent the user's selection and a colorOptions property implemented as a Collection (of strings) to store the available color choices. Assuming that you have defined the getters and setters for the colorSelected and colorOptions properties in your orderEntryForm form bean, you can render the pulldown list using:

The list will be populated using the strings in the colorOptions collection of the orderEntryForm and the value that the user selects will go into the colorSelected property that gets posted to the subsequent Action. Note that we are assuming here that the colorOptions property of the orderEntryForm has already been set.

See How can I prepopulate a form? for instructions on how to set form bean properties before rendering edit forms that expect properties to be pre-set.

Independent DTO An Action that retrieves a list of open orders (as an ArrayList of Order objects) can use a DTO independently of any form bean to transfer search results to the view. First, the Action's execute method performs the search and puts the DTO into the request:

ArrayList results = businessObject. executeSearch( searchParameters );

request.setAttribut e("searchResults ",results) ;

Then the view can iterate through the results using the "searchResults" request key to reference the DTO:

`

..other properties.. .

How can I scroll through list of pages like the search results in google?

Many Struts developers use the Pager from the JSPTags site.

http://jsptags. com/tags/ navigation/ pager/

Why do the Struts tags provide for so little formatting?

The Struts tags seem to provide only the most rudimentary functionality. Why is there not better support for date formatting and advanced string handling?

Three reasons:

First, work started on the JSTL and we didn't want to duplicate the effort.

Second, work started on Java Server Faces, and we didn't want to duplicate that effort either.

Third, in a Model 2 application, most of the formatting can be handled in the ActionForms (or in the business tier), so all the tag has to do is spit out a string. This leads to better reuse since the same "how to format" code does not need to be repeated in every instance. You can "say it once" in a JavaBean and be done with it. Why don't the Struts taglibs offer more layout options?

Since the Struts tags are open source, you can extend them to provide whatever additional formatting you may need. If you are interested in a pre-written taglib that offers more layout options, see the struts-layout taglib.

In the same arena, there is a well regarded contributor taglib that can help you create Menus for your Struts applications.

Why does the tag URL-encode javascript and mailto links?

The tag is not intended for use with client-side references like those used to launch Javascripts or email clients. The purpose of link tag is to interject the context (or module) path into the URI so that your server-side links are not dependent on your context (or module) name. It also encodes the link, as needed, to maintain the client's session on the server. Neither feature applies to client-side links, so there is no reason to use the tag. Simply markup the client-side links using the standard tag.

Why does the option tag render selected=selected instead of just selected?

Attribute minimization (that is, specifying an attribute with no value) is a place where HTML violates standard XML syntax rules. This matters a lot for people writing to browsers that support XHTML, where doing so makes the page invalid. It's much better for Struts to use the expanded syntax, which works the same on existing browsers interpreting HTML, and newer browsers that expect XHTML-compliant syntax. Struts is following the behavior recommended by the XHTML specification

Do I have to use JSPs with my application?

The short answer to this question is: No, you are not limited to JavaServer Pages.

The longer answer is that you can use any type of presentation technology which can be returned by a web server or Java container. The list includes but is not limited to:

* JavaServer Pages,

* HTML pages,

* WML files,

* Java servlets,

* Velocity templates, and

* XML/XLST

Some people even mix and match apparently unrelated technologies, like PHP, into the same web application.

Do ActionForms have to be true JavaBeans?

ActionForms are added to a servlet scope (session or request) as beans. What this means is that, for certain functionality to be available, your ActionForms will have to follow a few simple rules.

First, your ActionForm bean must have a zero-arguments constructor. This is required because Struts must be able to dynamically create new instances of your form bean class, while knowing only the class name. This is not an onerous restriction, however, because Struts will also populate your form bean's properties (from the request parameters) for you.

Second, the fields of your form bean are made available to the framework by supplying public getter and setter methods that follow the naming design patterns described in the JavaBeans Specification. For most users, that means using the following idiom for each of your form bean's properties:

private {type} fieldName;

public {type} getFieldName( ) {

return (this.fieldName) ;

}

public void setFieldName( {type} fieldName) {

this.fieldName = fieldName;

}

NOTE - you MUST obey the capitalization conventions shown above for your ActionForm properties to be recognized. The property name in this example is "fieldName", and that must also be the name of the input field that corresponds to this property. A bean property may have a "getter" method and a "setter" method (in a form bean, it is typical to have both) whose name starts with "get" or "set", followed by the property name with the first character capitalized. (For boolean properties, it is also legal to use "is" instead of "get" as the prefix for the getter method.)

Advanced JavaBeans users will know that you can tell the system you want to use different names for the getter and setter methods, by using a java.beans.BeanInfo class associated with your form bean. Normally, however, it is much more convenient to follow the standard conventions.

WARNING - developers might be tempted to use one of the following techniques, but any of them will cause your property not to be recognized by the JavaBeans introspection facilities, and therefore cause your applications to misbehave:

* Using getter and setter method names that do not match - if you have a getFoo() method for your getter, but a setBar() method for your setter, Java will not recognize these methods as referring to the same property. Instead, the language will think you have a read-only property named "foo" and a write-only property named "bar".

* Using more than one setter method with the same name - The Java language lets you "overload" methods, as long as the argument types are different. For example, you could have a setStartDate( java.util. Date date) method and a setStartDate( String date) method in the same class, and the compiled code would know which method to call based on the parameter type being passed. However, doing this for form bean properties will prevent Java from recognizing that you have a "startDate" property at all.

There are other rules to follow if you want other features of your form beans to be exposed. These include indexed attributes and mapped attributes. They are covered in detail in other areas of the Struts documentation, in particular: indexedprops. html

Do I have to have a separate ActionForm bean for every HTML form?

This is an interesting question. As a newbie, it is a good practice to create a new ActionForm for each action sequence. You can use DynaActionForms to help reduce the effort required, or use the code generation facilities of your IDE.

Some issues to keep in mind regarding reuse of form beans are as follows:

* Validation - You might need to use different validation rules depending upon the action that is currently being executed.

* Persistence - Be careful that a form populated in one action is not unexpectedly reused in a different action. Multiple entries in struts-config. xml for the same ActionForm subclass can help (especially if you store your form beans in session scope). Alternatively, storing form beans in request scope can avoid unexpected interactions (as well as reduce the memory footprint of your application, because no server-side objects will need to be saved in between requests.

* Checkboxes - If you do as recommended and reset your boolean properties (for fields presented as checkboxes), and the page you are currently displaying does not have a checkbox for every boolean property on the form bean, the undisplayed boolean properties will always appear to have a false value.

* Workflow - The most common need for form bean reuse is workflow. Out of the box, Struts has limited support for workflow, but a common pattern is to use a single form bean with all of the properties for all of the pages of a workflow. You will need a good understanding of the environment (ActionForms, Actions, etc.) prior to being able to put together a smooth workflow environment using a single form bean.

As you get more comfortable, there are a few shortcuts you can take in order to reuse your ActionForm beans. Most of these shortcuts depend on how you have chosen to implement your Action / ActionForm combinations.

How can I prepopulate a form?

The simplest way to prepopulate a form is to have an Action whose sole purpose is to populate an ActionForm and forward to the servlet or JSP to render that form back to the client. A separate Action would then be use to process the submitted form fields, by declaring an instance of the same form bean name.

The struts-example example application that is shipped with Struts illustrates this design pattern nicely. Note the following definitions from the struts-config. xml file:

...

...

<-- Registration form bean -->

type="org.apache. struts.webapp. example.Registra tionForm" />

...

...

...

<-- Edit user registration -->

type="org.apache. struts.webapp. example.EditRegi strationAction"

name="registrationF orm"

scope="request"

validate="false" />

...

<-- Save user registration -->

type="org.apache. struts.webapp. example.SaveRegi strationAction"

name="registrationF orm"

input="registration "

scope="request" />

...

Note the following features of this approach:

* Both the /editRegistration and /saveRegistration actions use the same form bean.

* When the /editRegistration action is entered, Struts will have pre-created an empty form bean instance, and passed it to the execute() method. The setup action is free to preconfigure the values that will be displayed when the form is rendered, simply by setting the corresponding form bean properties.

* When the setup action completes configuring the properties of the form bean, it should return an ActionForm that points at the page which will display this form. If you are using the Struts JSP tag library, the action attribute on your tag will be set to /saveRegistration in order for the form to be submitted to the processing action.

* Note that the setup action (/editRegistration) turns off validation on the form that is being set up. You will normally want to include this attribute in the configuration of your setup actions, because you are not planning to actually process the results -- you simply want to take advantage of the fact that Struts will precreate a form bean instance of the correct class for you.

* The processing action (/saveRegistration) , on the other hand, leaves out the validate attribute, which defaults to true. This tells Struts to perform the validations associated with this form bean before invoking the processing action at all. If any validation errors have occurred, Struts will forward back to your input page (technically, it forwards back to an ActionForward named "registration" in this case, because the example webapp uses the inputForward attribute in the element -- see the documentation describing struts-config. xml for more information) instead of calling your processing action.

Can I have an Action without a form?

Yes. If your Action does not need any data and it does not need to make any data available to the view orcontroller component that it forwards to, it doesn't need

a form. A good example of an Action with no ActionForm is the LogoffAction in the struts example application:

type="org.apache. struts.webapp. example.LogoffAc tion">

This action needs no data other than the user's session, which it can get from the Request, and it doesn't need to prepare anyview elements for display, so it does not need a form.

However, you cannot use the tag without an ActionForm. Even if you want to use the tag with a simple Action that does not require input, the tag will expect you to use some type of ActionForm, even if it is an empty subclass without any properties.

SQL Interview Questions

What is RDBMS?

Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers.

This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.

What is normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

What are different normalization forms?

1NF: Eliminate Repeating Groups

Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.

2NF: Eliminate Redundant Data

If an attribute depends on only part of a multi-valued key, remove it to a separate table.

3NF: Eliminate Columns Not Dependent On Key

If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key

BCNF: Boyce-Codd Normal Form

If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.

4NF: Isolate Independent Multiple Relationships

No table may contain two or more 1:n or n:m relationships that are not directly related.

5NF: Isolate Semantically Related Multiple Relationships

There may be practical constrains on information that justify separating logically related many-to-many relationships.

ONF: Optimal Normal Form

A model limited to only simple (elemental) facts, as expressed in Object Role Model notation.

DKNF: Domain-Key Normal Form

A model free from all modification anomalies.

Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database.

What is Stored Procedure?

A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.

e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What is Trigger?

A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table.

Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a

specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.

Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the

trigger is fired because of data modification it can also cause another data modification, thereby firing

another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is View?

A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as

updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the

view was created with. It should also be noted that as data in the original table changes, so does data

in the view, as views are the way to look at part of the original table. The results of using a view are

not permanently stored in the database. The data accessed through a view is actually constructed using

standard T-SQL select command and can come from one to many different base tables or even other

views.

What is Index?

An index is a physical structure containing pointers to the data. Indices are created in an existing table

to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of

a table, and each index is given a name. The users cannot see the indexes, they are just used to speed

up queries. Effective indexes are one of the best ways to improve performance in a database

application. A table scan happens when there is no index available to help a query. In a table scan SQL

Server examines every row in the table to satisfy the query results. Table scans are sometimes

unavoidable, but on large tables, scans have a terrific impact on performance.

Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this

reason, each database table may have only one clustered index.

Non-clustered indexes are created outside of the database table and contain a sorted list of references

to the table itself.

What is the difference between clustered and a non-clustered index?

A clustered index is a special type of index that reorders the way records in the table are physically

stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain

the data pages.

A nonclustered index is a special type of index in which the logical order of the index does not match

the physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of

the data pages. Instead, the leaf nodes contain index rows.

What are the different index configurations a table can have?

A table can have one of the following index configurations:

No indexes

A clustered index

A clustered index and many nonclustered indexes

A nonclustered index

Many nonclustered indexes

What is cursors?

Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis,

instead of the typical SQL commands that operate on all the rows in the set at one time.

In order to work with a cursor we need to perform some steps in the following order:

Declare cursor

Open cursor

Fetch row from the cursor

Process fetched row

Close cursor

Deallocate cursor

What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of

the databases, i.e., maintenance, validation task and status checks.

E.g. DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.

DBCC CHECKALLOC - To check that all pages in a db are correctly allocated.

DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query

both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy

to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data.

Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.

What is Collation?

Collation refers to a set of rules that determine how data is sorted and compared. Character data is

sorted using rules that define the correct character sequence, with options for specifying casesensitivity,

accent marks, kana character types and character width.

What are different type of Collation Sensitivity?

Case sensitivity

A and a, B and b, etc.

Accent sensitivity

a and á, o and ó, etc.

Kana Sensitivity

When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana

sensitive.

Width sensitivity

When a single-byte character (half-width) and the same character when represented as a double-byte

character (full-width) are treated differently then it is width sensitive.

What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by

default primary key creates a clustered index on the column, where are unique creates a nonclustered

index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key

allows one NULL only.

How to implement one-to-one, one-to-many and many-to-many relationships while

designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary

and foreign key relationships.

One-to-Many relationships are implemented by splitting the data into two tables with primary key and

foreign key relationships.

Many-to-Many relationships are implemented using a junction table with the keys from both the tables

forming the composite primary key of the junction table.

What is a NOLOCK?

Using the NOLOCK query optimiser hint is generally considered good practice in order to improve

concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are

taken when data is read. The result is a Dirty Read, which means that another process could be

updating the data at the exact time you are reading it. There are no guarantees that your query will

retrieve the most recent data. The advantage to performance is that your reading of data will not block

updates from taking place, and updates will not block your reading of data. SELECT statements take

Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but

other processes are blocked from modifying the data. The updates will queue until all the reads have

completed, and reads requested after the update will wait for the updates to complete. The result to

your system is delay(blocking).

What is difference between DELETE & TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHERE

clause. Truncate will actually remove all the rows from a table and there will be no data in the table

after we run the truncate command.

TRUNCATE

TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.

TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the

page deallocations are recorded in the transaction log.

TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes

and so on remain. The counter used by an identity for new rows is reset to the seed for the column.

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.

Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

TRUNCATE can not be Rolled back.

TRUNCATE is DDL Command.

TRUNCATE Resets identity of the table.

DELETE

DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.

If you want to retain the identity counter, use DELETE instead. If you want to remove table definition

and its data, use the DROP TABLE statement.

DELETE Can be used with or without a WHERE clause

DELETE Activates Triggers.

DELETE Can be Rolled back.

DELETE is DML Command.

DELETE does not reset identity of the table.

Difference between Function and Stored Procedure?

UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as

Stored procedures cannot be.

UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.

Inline UDF's can be though of as views that take parameters and can be used in JOINs and other

Rowset operations.

When is the use of UPDATE_STATISTICS command?

This command is basically used when a large processing of data has occurred. If a large amount of

deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to

take these changes into account. UPDATE_STATISTICS updates the indexes on these tables

accordingly.

What types of Joins are possible with Sql Server?

Joins are used in queries to explain how different tables are related. Joins also let you select data from

a table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT

OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT

statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING

behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a

query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

What is sub-query? Explain properties of sub-query.

Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed

arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of

parentheses. Sub-queries are generally used to return a single row as an atomic value, though they

may be used to compare values against multiple rows with the IN keyword.

A subquery is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT

statement if executed independently of the T-SQL statement, in which it is nested, will return a result

set. Meaning a subquery SELECT statement can standalone and is not depended on the statement in

which it is nested. A subquery SELECT statement can return any number of values, and can be found

in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a

T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery

can be used anywhere an expression can be used.

Properties of Sub-Query

A subquery must be enclosed in the parenthesis.

A subquery must be put in the right hand of the comparison operator, and

A subquery cannot contain a ORDER-BY clause.

A query can contain more than one sub-queries.

What are types of sub-queries?

Single-row subquery, where the subquery returns only one row.

Multiple-row subquery, where the subquery returns multiple rows,.and

Multiple column subquery, where the subquery returns multiple columns.

What is SQL Profiler?

SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of

Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to

analyze later. For example, you can monitor a production environment to see which stored procedures

are hampering performance by executing too slowly.

Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too

large, you can filter them based on the information you want, so that only a subset of the event data is

collected. Monitoring too many events adds overhead to the server and the monitoring process and can

cause the trace file or trace table to grow very large, especially when the monitoring process takes

place over a long period of time.

What is User Defined Functions?

User-Defined Functions allow to define its own T-SQL functions that can accept 0 or more parameters

and return a single scalar data value or a table data type.

What kind of User-Defined Functions can be created?

There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-

Valued and Multi-statement Table-valued.

Scalar User-Defined Function

A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp

data types are not supported. These are the type of user-defined functions that most developers are

used to in other programming languages. You pass in 0 to many parameters and you get a return

value.

Inline Table-Value User-Defined Function

An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative

to a view as the user-defined function can pass parameters into a T-SQL select command and in

essence provide us with a parameterized, non-updateable view of the underlying tables.

Multi-statement Table-Value User-Defined Function

A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional

alternative to a view as the function can support multiple T-SQL statements to build the final result

where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a TSQL

select command or a group of them gives us the capability to in essence create a parameterized,

non-updateable view of the data in the underlying tables. Within the create function command you

must define the table structure that is being returned. After creating this type of user-defined function,

It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored

procedure which can also return record sets.

Which TCP/IP port does SQL Server run on? How can it be changed?

SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties –> Port

number.both on client and the server.

What are the authentication modes in SQL Server? How can it be changed?

Windows mode and mixed mode (SQL & Windows).

To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL

Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group.

Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the

Security page.

Where are SQL server users names and passwords are stored in sql server?

They get stored in master db in the sysxlogins table.

Which command using Query Analyzer will give you the version of SQL server and operating

system?

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY

('edition')

What is SQL server agent?

SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It

is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the

implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to

schedule your own jobs and scripts.

Can a stored procedure call itself or recursive stored procedure? How many level SP nesting

possible?

Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves.

Recursion can be defined as a method of problem solving wherein the solution is arrived at by

repetitively applying it to subsets of the problem. A common application of recursive logic is to perform

numeric computations that lend themselves to repetitive evaluation by the same processing steps.

Stored procedures are nested when one stored procedure calls another or executes managed code by

referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code

references up to 32 levels.

What is @@ERROR?

The @@ERROR automatic variable returns the error code of the last Transact-SQL statement. If there

was no error, @@ERROR returns zero. Because @@ERROR is reset after each Transact-SQL statement,

it must be saved to a variable if it is needed to process it further after checking it.

What is Raiseerror?

Stored procedures report errors to client applications via the RAISERROR command. RAISERROR

doesn't change the flow of a procedure; it merely displays an error message, sets the @@ERROR

automatic variable, and optionally writes the message to the SQL Server error log and the NT

application event log.

What is log shipping?

Log shipping is the process of automating the backup of database and transaction log files on a

production SQL server, and then restoring them onto a standby server. Enterprise Editions only

supports log shipping. In log shipping the transactional log file from one server is automatically updated

into the backup database on the other server. If one server fails, the other server will have the same db

can be used this as the Disaster Recovery plan. The key feature of log shipping is that is will

automatically backup transaction logs throughout the day and automatically restore them on the

standby server at defined interval.

What is the difference between a local and a global variable?

A local temporary table exists only for the duration of a connection or, if defined inside a compound

statement, for the duration of the compound statement.

A global temporary table remains in the database permanently, but the rows exist only within a given

connection. When connection are closed, the data in the global temporary table disappears. However,

the table definition remains with the database for access when database is opened next time.

What command do we use to rename a db?

sp_renamedb ‘oldname’ , ‘newname’

If someone is using db it will not accept sp_renmaedb. In that case first bring db to single user using

sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user

mode.

What is sp_configure commands and set commands?

Use sp_configure to display or change server-level settings. To change database-level settings, use

ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.

What are the different types of replication? Explain.

The SQL Server 2000-supported replication types are as follows:

· Transactional

· Snapshot

· Merge

Snapshot replication distributes data exactly as it appears at a specific moment in time and does not

monitor for updates to the data. Snapshot replication is best used as a method for replicating data that

changes infrequently or where the most up-to-date values (low latency) are not a requirement. When

synchronization occurs, the entire snapshot is generated and sent to Subscribers.

Transactional replication, an initial snapshot of data is applied at Subscribers, and then when data

modifications are made at the Publisher, the individual transactions are captured and propagated to

Subscribers.

Merge replication is the process of distributing data from Publisher to Subscribers, allowing the

Publisher and Subscribers to make updates while connected or disconnected, and then merging the

updates between sites when they are connected.

What are the OS services that the SQL Server installation adds?

MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac co-ordinator)

What are three SQL keywords used to change or set someone’s permissions?

GRANT, DENY, and REVOKE.

What does it mean to have quoted_identifier on? What are the implications of having it off?

When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and

literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers

cannot be quoted and must follow all Transact-SQL rules for identifiers.

What is the STUFF function and how does it differ from the REPLACE function?

STUFF function to overwrite existing characters. Using this syntax, STUFF(string_expression, start,

length, replacement_characters), string_expression is the string that will have characters substituted,

start is the starting position, length is the number of characters in the string that are substituted, and

replacement_characters are the new characters interjected into the string.

REPLACE function to replace existing characters of all occurance. Using this syntax

REPLACE(string_expression, search_string, replacement_string), where every incidence of

search_string found in the string_expression will be replaced with replacement_string.

Using query analyzer, name 3 ways to get an accurate count of the number of records in a

table?

SELECT * FROM table1

SELECT COUNT(*) FROM table1

SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid <>

How to rebuild Master Database?

Shutdown Microsoft SQL Server 2000, and then run Rebuildm.exe. This is located in the Program

Files\Microsoft SQL Server\80\Tools\Binn directory.

In the Rebuild Master dialog box, click Browse.

In the Browse for Folder dialog box, select the \Data folder on the SQL Server 2000 compact disc or in

the shared network directory from which SQL Server 2000 was installed, and then click OK.

Click Settings. In the Collation Settings dialog box, verify or change settings used for the master

database and all other databases.

Initially, the default collation settings are shown, but these may not match the collation selected during

setup. You can select the same settings used during setup or select new collation settings. When done,

click OK.

In the Rebuild Master dialog box, click Rebuild to start the process.

The Rebuild Master utility reinstalls the master database.

To continue, you may need to stop a server that is running.

Source: http://msdn2.microsoft.com/en-us/library/aa197950(SQL.80).aspx

What is the basic functions for master, msdb, model, tempdb databases?

The Master database holds information for all databases located on the SQL Server instance and is the

glue that holds the engine together. Because SQL Server cannot start without a functioning master

database, you must administer this database with care.

The msdb database stores information regarding database backups, SQL Agent information, DTS

packages, SQL Server jobs, and some replication information such as for log shipping.

The tempdb holds temporary objects such as global and local temporary tables and stored procedures.

The model is essentially a template database used in the creation of any new user database created in

the instance.

What are primary keys and foreign keys?

Primary keys are the unique identifiers for each row. They must contain unique values and cannot be

null. Due to their importance in relational databases, Primary keys are the most fundamental of all keys

and constraints. A table can have only one Primary key.

Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship

between tables.

What is data integrity? Explain constraints?

Data integrity is an important feature in SQL Server. When used properly, it ensures that data is

accurate, correct, and valid. It also acts as a trap for otherwise undetectable bugs within applications.

A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should

have a primary key constraint to uniquely identify each row and only one primary key constraint can be

created for each table. The primary key constraints are used to enforce entity integrity.

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values

are entered. The unique key constraints are used to enforce entity integrity as the primary key

constraints.

A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the

corresponding data values. A foreign key in one table points to a primary key in another table. Foreign

keys prevent actions that would leave rows with foreign key values when there are no primary keys

with that value. The foreign key constraints are used to enforce referential integrity.

A CHECK constraint is used to limit the values that can be placed in a column. The check constraints

are used to enforce domain integrity.

A NOT NULL constraint enforces that the column will not accept null values. The not null constraints

are used to enforce domain integrity, as the check constraints.

What are the properties of the Relational tables?

Relational tables have six properties:

· Values are atomic.

· Column values are of the same kind.

· Each row is unique.

· The sequence of columns is insignificant.

· The sequence of rows is insignificant.

· Each column must have a unique name.

What is De-normalization?

De-normalization is the process of attempting to optimize the performance of a database by adding

redundant data. It is sometimes necessary because current DBMSs implement the relational model

poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while

providing physical storage of data that is tuned for high performance. De-normalization is a technique

to move from higher to lower normal forms of database modeling in order to speed up database access.

How to get @@error and @@rowcount at the same time?

If @@Rowcount is checked after Error checking statement then it will have 0 as the value of

@@Recordcount as it would have been reset.

And if @@Recordcount is checked before the error-checking statement then @@Error would get reset.

To get @@error and @@rowcount at the same time do both in same statement and store them in local

variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

What is Identity?

Identity (or AutoNumber) is a column that automatically generates numeric values. A start and

increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers,

the value of this cannot be controled. Identity/GUID columns do not need to be indexed.

What is a Scheduled Jobs or What is a Scheduled Tasks?

Scheduled tasks let user automate processes that run on regular or predictable cycles. User can

schedule administrative tasks, such as cube processing, to run during times of slow business activity.

User can also determine the order in which tasks run by creating job steps within a SQL Server Agent

job. E.g. Back up database, Update Stats of Tables. Job steps give user control over flow of execution.

If one job fails, user can configure SQL Server Agent to continue to run the remaining tasks or to stop

execution.

What is a table called, if it does not have neither Cluster nor Non-cluster Index? What is it

used for?

Unindexed table or Heap. Microsoft Press Books and Book On Line (BOL) refers it as Heap.

A heap is a table that does not have a clustered index and, therefore, the pages are not linked by

pointers. The IAM pages are the only structures that link the pages in a table together.

Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table

and than do bulk of inserts and to restore those indexes after that.

What is BCP? When does it used?

BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the

structures same as source to destination.

How do you load large data to the SQL server database?

BulkCopy is a tool used to copy huge amount of data from tables. BULK INSERT command helps to

Imports a data file into a database table or view in a user-specified format.

Can we rewrite subqueries into simple select statements or with joins?

Subqueries can often be re-written to use a standard outer join, resulting in faster performance. As we

may know, an outer join uses the plus sign (+) operator to tell the database to return all non-matching

rows with NULL values. Hence we combine the outer join with a NULL test in the WHERE clause to

reproduce the result set without using a sub-query.

Can SQL Servers linked to other servers like Oracle?

SQL Server can be lined to any server provided it has OLE-DB provider from Microsoft to allow a link.

E.g. Oracle has a OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL

Server group.

How to know which index a table is using?

SELECT table_name,index_name FROM user_constraints

How to copy the tables, schema and views from one SQL server to another?

Microsoft SQL Server 2000 Data Transformation Services (DTS) is a set of graphical tools and

programmable objects that lets user extract, transform, and consolidate data from disparate sources

into single or multiple destinations.

What is Self Join?

This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self

join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it

involves a relationship with only one table. The common example is when company have a hierarchal

reporting structure whereby one member of staff reports to another.

What is Cross Join?

A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved

in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied

by the number of rows in the second table. The common example is when company wants to combine

each product with a pricing table to analyze each product at each price.

Which virtual table does a trigger use?

Inserted and Deleted.

List few advantages of Stored Procedure.

· Stored procedure can reduced network traffic and latency, boosting application performance.

· Stored procedure execution plans can be reused, staying cached in SQL Server's memory,

reducing server overhead.

· Stored procedures help promote code reuse.

· Stored procedures can encapsulate logic. You can change stored procedure code without

affecting clients.

· Stored procedures provide better security to your data.

What is DataWarehousing?

· Subject-oriented, meaning that the data in the database is organized so that all the data

elements relating to the same real-world event or object are linked together;

· Time-variant, meaning that the changes to the data in the database are tracked and recorded

so that reports can be produced showing changes over time;

· Non-volatile, meaning that data in the database is never over-written or deleted, once

committed, the data is static, read-only, but retained for future reporting;

· Integrated, meaning that the database contains data from most or all of an organization's

operational applications, and that this data is made consistent.

What is OLTP(OnLine Transaction Processing)?

In OLTP - online transaction processing systems relational database design use the discipline of data

modeling and generally follow the Codd rules of data normalization in order to ensure absolute data

integrity. Using these rules complex information is broken down into its most simple structures (a table)

where all of the individual atomic level elements relate to each other and satisfy the normalization

rules.

How do SQL server 2000 and XML linked? Can XML be used to access data?

FOR XML (ROW, AUTO, EXPLICIT)

You can execute SQL queries against existing relational databases to return results as XML rather than

standard rowsets. These queries can be executed directly or from within stored procedures. To retrieve

XML results, use the FOR XML clause of the SELECT statement and specify an XML mode of RAW, AUTO,

or EXPLICIT.

OPENXML

OPENXML is a Transact-SQL keyword that provides a relational/rowset view over an in-memory XML

document. OPENXML is a rowset provider similar to a table or a view. OPENXML provides a way to

access XML data within the Transact-SQL context by transferring data from an XML document into the

relational tables. Thus, OPENXML allows you to manage an XML document and its interaction with the

relational environment.

What is an execution plan? When would you use it? How would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods

chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful

tool for a developer to understand the performance characteristics of a query or stored procedure since

the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or

query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query

drop-down menu). If this option is turned on it will display query execution plan in separate window

when query is ran again.

Subqueries

Subqueries are queries embedded in queries. They are used to retrieve data from one table based on data in another table. They generally are used when tables have some kind of relationship. For example, in the Northwind database, the Orders table has a CustomerID field, which references a customer in the Customers table. Retrieving the CustomerID for a specific order is pretty straightforward.

Code Sample: SubqueriesJoinsUnions/Demos/Subquery-SelectCustomerID.sql

/*

Find the CustomerID of the company that placed order 10290.

*/

SELECT CustomerID

FROM Orders

WHERE OrderID = 10290;

Code Explanation

This will return COMMI, which is very likely meaningless to the people reading the report. The next query uses a subquery to return a meaningful result.

Code Sample: SubqueriesJoinsUnions/Demos/Subquery-SelectCompanyName.sql

-- Find the name of the company that placed order 10290.

SELECT CompanyName

FROM Customers

WHERE CustomerID = (SELECT CustomerID

FROM Orders

WHERE OrderID = 10290);

Code Sample: SubqueriesJoinsUnions/Demos/Subquery-IN.sql

-- Find the Companies that placed orders in 1997

/******************************

Both of the queries below will work in SQL Server

Oracle

******************************/

SELECT CompanyName

FROM Customers

WHERE CustomerID IN (SELECT CustomerID

FROM Orders

WHERE OrderDate BETWEEN '1-Jan-1997' AND '31-Dec-1997');

/******************************

Code Sample: SubqueriesJoinsUnions/Demos/Joins-EmployeeOrders.sql

-- Create a report showing employee orders.

SELECT Employees.EmployeeID, Employees.FirstName,

Employees.LastName, Orders.OrderID, Orders.OrderDate

FROM Employees JOIN Orders ON

(Employees.EmployeeID = Orders.EmployeeID)

ORDER BY Orders.OrderDate;

Code Sample: AdvancedSelects/Demos/Concatenate-Oracle.sql

-- Select the full name of all employees. Oracle.

SELECT FirstName || ' ' || LastName

FROM Employees;

Aliases

You will notice in the examples above that the calculated columns have the header "(No column name)". The keyword AS is used to provide a named header for the column.

ode Sample: AdvancedSelects/Demos/Alias.sql

SELECT OrderID, Freight, Freight * 1.1 AS FreightTotal

FROM Orders

WHERE Freight >= 500;

/******************************

Oracle and MySQL

******************************/

SELECT SUM(Quantity) AS TotalUnits

FROM Order_Details

WHERE ProductID=3;

Code Sample: AdvancedSelects/Demos/Aggregate-Avg.sql

-- Find the Average Unit Price of Products

SELECT AVG(UnitPrice) AS AveragePrice

FROM Products;

Code Explanation

Returns 28.8663.

Code Sample: AdvancedSelects/Demos/Aggregate-MinMax.sql

-- Find the Earliest and Latest Dates of Hire

SELECT MIN(HireDate) AS FirstHireDate,

MAX(HireDate) AS LastHireDate

FROM Employees;

ode Sample: AdvancedSelects/Demos/Aggregate-GroupBy.sql

--Retrieve the number of employees in each city

SELECT City, COUNT(EmployeeID) AS NumEmployees

FROM Employees

GROUP BY City;

HAVING

The HAVING clause is used to filter grouped data. For example, the following code specifies that we only want information on cities that have more than one employee.

Code Sample: AdvancedSelects/Demos/Aggregate-Having.sql

/*

Retrieve the number of employees in each city

in which there are at least 2 employees.

*/

SELECT City, COUNT(EmployeeID) AS NumEmployees

FROM Employees

GROUP BY City

HAVING COUNT(EmployeeID) > 1;

Code Sample: AdvancedSelects/Demos/Aggregate-OrderOfClauses.sql

/*

Find the number of sales representatives in each city that contains

at least 2 sales representatives. Order by the number of employees.

*/

SELECT City, COUNT(EmployeeID) AS NumEmployees

FROM Employees

WHERE Title = 'Sales Representative'

GROUP BY City

HAVING COUNT(EmployeeID) > 1

ORDER BY NumEmployees;

Selecting Distinct Records

The DISTINCT keyword is used to select distinct combinations of column values from a table. For example, the following example shows how you would find all the distinct cities in which Northwind has employees.

Code Sample: AdvancedSelects/Demos/Distinct.sql

/*

Find all the distinct cities in which Northwind has employees.

*/

SELECT DISTINCT City

FROM Employees

ORDER BY City

DISTINCT is often used with aggregate functions. The following example shows how DISTINCT can be used to find out in how many different cities Northwind has employees.

Code Sample: AdvancedSelects/Demos/Distinct-Count.sql

/*

Find out in how many different cities Northwind has employees.

*/

SELECT COUNT(DISTINCT City) AS NumCities

FROM Employees

Built-in Data Manipulation Functions

In this section, we will discuss some of the more common built-in data manipulation functions. Unfortunately, the functions differ greatly between databases, so you should be sure to check your database documentation when using these functions.

The tables below show some of the more common math, string, and date functions.

Common Math Functions

Common Math Functions

Description SQL Server Oracle MySQL

Absolute value ABS ABS ABS

Smallest integer >= value CEILING CEIL CEILING

Round down to nearest integer FLOOR FLOOR FLOOR

Power POWER POWER POWER

Round ROUND ROUND ROUND

Square root SQRT SQRT SQRT

Formatting numbers to two decimal places CAST(num AS decimal(8,2)) TO_CHAR(num,'9.00') FORMAT(num,2) or CAST(num AS decimal(8,2))

Code Sample: AdvancedSelects/Demos/Functions-Math1.sql

/*

Select freight as is and

freight rounded to the first decimal (e.g, 1.150 becomes 1.200)

from the Orders tables

*/

SELECT Freight, ROUND(Freight,1) AS ApproxFreight

FROM Orders;

Common String Functions

Common String Functions

Description SQL Server Oracle MySQL

Convert characters to lowercase LOWER LOWER LOWER

Convert characters to uppercase UPPER UPPER UPPER

Remove trailing blank spaces RTRIM RTRIM RTRIM

Remove leading blank spaces LTRIM LTRIM LTRIM

Substring SUBSTRING SUBSTR SUBSTRING

Code Sample: AdvancedSelects/Demos/Functions-String1.sql

/*

Select first and last name from employees in all uppercase letters

*/

SELECT UPPER(FirstName), UPPER(LastName)

FROM Employees;

Common Date Functions

Common Date Functions

Description SQL Server Oracle MySQL

Date addition DATEADD (use +) DATE_ADD

Date subtraction DATEDIFF (use -) DATEDIFF

Convert date to string DATENAME TO_CHAR DATE_FORMAT

Convert date to number DATEPART TO_NUMBER(TO_CHAR) EXTRACT

Get current date and time GETDATE SYS_DATE NOW

Code Sample: AdvancedSelects/Demos/Functions-Date1.sql

-- Find the hiring age of each employee

/******************************

SQL Server

******************************/

SELECT LastName, BirthDate, HireDate, DATEDIFF(year,BirthDate,HireDate) AS HireAge

FROM Employees

ORDER BY HireAge;

/******************************

Oracle

******************************/

SELECT LastName, BirthDate, HireDate, FLOOR((HireDate - BirthDate)/365.25) AS HireAge

FROM Employees

ORDER BY HireAge;

ode Sample: AdvancedSelects/Demos/Functions-Date2.sql

-- Find the Birth month for every employee

/******************************

SQL Server

******************************/

SELECT FirstName, LastName, DATENAME(month,BirthDate) AS BirthMonth

FROM Employees

ORDER BY DATEPART(month,BirthDate);

/******************************

Oracle

******************************/

SELECT FirstName, LastName, TO_CHAR(BirthDate,'MONTH') AS BirthMonth

FROM Employees

ORDER BY TO_NUMBER(TO_CHAR(BirthDate,'MM'));

INSERT

To insert a record into a table, you must specify values for all fields that do not have default values and cannot be NULL.

Syntax

INSERT INTO table

(columns)

VALUES (values);

UPDATE

The UPDATE statement allows you to update one or more fields for any number of records in a table. You must be very careful not to update more records than you intend to!

Syntax

UPDATE table

SET field = value,

field = value,

field = value

WHERE conditions;

DELETE

The DELETE statement allows you to delete one or more records in a table. Like with UPDATE, you must be very careful not to delete more records than you intend to!

Syntax

DELETE FROM Employees

WHERE conditions;

Creating Tables

Now that you understand data types, you're ready to learn how to create a table. Note that you must have the proper database permissions to do so.

Syntax

CREATE TABLE table_name

(

column_name data_type,

column_name data_type,

column_name data_type,

more columns...

)

Creating Views

To create views, simply write your SELECT query and wrap it in a CREATE VIEW statement as shown below.

Syntax

CREATE VIEW view_name AS

SELECT statement goes here...

Here is an example showing how to create a view from a complicated query we've seen earlier.

Code Sample: Views/Demos/CreateView.sql

--create view showing detailed order information

CREATE VIEW vwOrderInfo AS

SELECT o.OrderID, o.OrderDate, o.RequiredDate, o.ShippedDate, c.CompanyName, e.FirstName, e.LastName

FROM Orders o

JOIN Employees e ON (e.EmployeeID = o.EmployeeID)

JOIN Customers c ON (c.CustomerID = o.CustomerID);

--Select all records from view that were shipped after the required date

SELECT *

FROM vwOrderInfo

WHERE RequiredDate <>

Creating Stored Procedures

Stored procedures are created with the CREATE PROCEDURE statement. The syntax is shown below.

Syntax

CREATE PROCEDURE procedure_name

@param data_type = default_value,

@param data_type = default_value,

@param data_type = default_value

AS

-- statements for procedure here