JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Networking Interview Questions

June 6, 2011 by Krishna Srinivasan Leave a Comment

Networking Interview Questions

(Hands on tips for cracking the interview)

Description

Technical interviews are largely focused on assessing your knowledge and skills on a specific technology or subject matter. Preparing for a technical job interview could be an uphill task, where you would need to scan voluminous books and material from numerous sources spread across different media. Wouldn’t your efforts be reduced greatly if you get a book specifically devoted towards the technical interviews on the respective technology/subject matter? A new book by Dreamtech Press, Networking Interview Questions ( May 02, 2011, INR.199/-, ISBN: 978-81-7722-795-6 ) bringing to you an economical and time-saving ensemble of probable questions being asked in the technical interviews, and their adequate answers and explanations.
This book will help the reader in preparing for an interview and reviewing all the important topics that are needed to be known by beginners as well as professionals in Networking. This book covers the valuable information on the concepts of Network Cards, Cabling, Topologies and Protocol Suites, Network Services and Communication Devices, Networking with Microsoft Windows, Managing Client and Server Computers, Managing NTFS Permission, Monitoring Server Health and Security, Managing Active Directory and Services, TCP/IP Administration, Dynamic Host Configuration Protocol and Managing IIS, Cisco IOS Software Fundamentals, IOS Reference Model, LAN’s Bridges and Switches and TCP/IP and IP Routing, Routing and Routing Protocol, WAN Protocol and Security.

About the Authors

Pradeep Mathur is founder of Divyamm Solutions, a comprehensive technical writing solutions provider to suite various business needs. He has ventured into technical writing after years of experience in technical support for world’s leading software and networking companies like Microsoft Inc. and Cisco Systems Inc. Besides being a management graduate, he also holds strong technical knowledge with an ability to simplify complex technical information into clear, compelling, and easyto-understand language. He holds various technical certifications: CCNA, MCSE, MCSA, MCDBA, IBM E-Commerce Professional.
The proficient team at Kogent Learning Solutions Inc. and Dreamtech Press has seized the market of computer books bringing excellent content in software development to the fore. The team is committed to excellence—excellence in quality of content, excellence in the dedication of its authors and editors, excellence in the attention to detail, and excellence in understanding the needs of its readers.

About Dreamtech Press

Dreamtech Press is one of the India’s leading IT, Management and Engineering books publisher, devoted to students and professionals, novices and experts, instructors and teachers. We have ardently analyzed and comprehended the needs of our readers. Moreover our meticulous care in creating and publishing our books; focusing on generic and specific educational requirements and demands of our readers makes us the best choice among readers. Efficacious process management and enduring quality processes have been hallmark towards our success.
Relationship Investing is the core of our business that has been the hallmark of our success. No wonder, respected global corporation – Apress/Springer, Manning Publication (USA), Source Books Inc., Career Press and W-Business have trusted our capability to deliver value in India. We have an exclusive sales and distribution with Wiley India Pvt. Ltd. wherein all the books printed by Dreamtech Press and distributed by Wiley India Pvt. Ltd.

Media Contact

Akash Kumar
Assistant Manager – Marketing & Public Relations
Cell: +91 987 383 8807
Email: akash.kumar@dreamtechpress.com

Filed Under: Interview Questions Tagged With: Networking

Weblogic Interview Questions

August 8, 2010 by Krishna Srinivasan Leave a Comment

1)How do I provide user credentials for starting a server?

When you create a domain, the Configuration Wizard prompts you to provide the username and password for an initial administrative user. If you create the domain in development mode, the wizard saves the username and encrypted password in a boot identity file. A WebLogic Server instance can refer to a boot identity file during its startup process. If a server instance does not find such a file, it prompts you to enter credentials.

If you create a domain in production mode, or if you want to change user credentials in an existing boot identity file, you can create a new boot identity file.

2)Can I start a Managed Server if the Administration Server is unavailable?

By default, if a Managed Server is unable to connect to the specified Administration Server during startup, it can retrieve its configuration by reading a configuration file and other files directly. You cannot change the server’s configuration until the Administration Server is available. A Managed Server that starts in this way is running in Managed Server Independence mode.

3)What is the function of T3 in WebLogic Server?

T3 provides a framework for WebLogic Server messages that support for enhancements. These enhancements include abbreviations and features, such as object replacement, that work in the context of WebLogic Server clusters and HTTP and other product tunneling. T3 predates Java Object Serialization and RMI, while closely tracking and leveraging these specifications. T3 is a superset of Java Object. Serialization or RMI; anything you can do in Java Object Serialization and RMI can be done over T3. T3 is mandated between WebLogic Servers and between programmatic clients and a WebLogic Server cluster. HTTP and IIOP are optional protocols that can be used to communicate between other processes and WebLogic Server. It depends on what you want to do. For example, when you want to communicate between a browser and WebLogic Server-use HTTP, or an ORB and WebLogic Server-IIOP.

4)How do you set the classpath?

WebLogic Server installs the following script that you can use to set the classpath that a server requires:

WL_HOME\server\bin\setWLSEnv.cmd (on Windows)

WL_HOME/server/bin/setWLSEnv.sh (on UNIX)

5)How do stubs work in a WebLogic Server cluster?

Clients that connect to a WebLogic Server cluster and look up a clustered object obtain a replica-aware stub for the object. This stub contains the list of available server instances that host implementations of the object. The stub also contains the load balancing logic for distributing the load among its host servers.

What happens when a failure occurs and the stub cannot connect to a WebLogic Server instance?

When the failure occurs, the stub removes the failed server instance from its list. If there are no servers left in its list, the stubb uses DNS again to find a running server and obtain a current list of running instances. Also, the stub periodically refreshes its list of available server instances in the cluster; this allows the stub to take advantage of new servers as they are added to the cluster.

6)How does a server know when another server is unavailable?

WebLogic Server uses two mechanisms to determine if a given server instance is unavailable.Each WebLogic Server instance in a cluster uses multicast to broadcast regular “heartbeat” messages that advertise its availability. By monitoring heartbeat messages, server instances in a cluster determine when a server instance has failed. The other server instances will drop a server instance from the cluster, if they do not receive three consecutive heartbeats from that server instance WebLogic Server also monitors socket errors to determine the availability of a
server instance. For example, if server instance A has an open socket to server instance B, and the socket unexpectedly closes, server A assumes that server B is offline.

7)How are notifications made when a server is added to a cluster?

The WebLogic Server cluster broadcasts the availability of a new server instance each time a new instance joins the cluster. Cluster-aware stubs also periodically update their list of available server instances.

8)How do clients handle DNS requests to failed servers?

If a server fails and DNS continues to send requests to the unavailable machine, this can waste bandwidth. For a Java client application, this problem occurs only during startup. WebLogic Server caches the DNS entries and removes the unavailable ones, to prevent the client from accessing a failed server twice. Failed servers can be more of a problem for browser-based clients, because they always use DNS. To avoid unnecessary DNS requests with browser-based clients, use a third-party load-balancer such as Resonate, BigIP, Alteon, and LocalDirector. These products mask multiple DNS addresses as a single address. They also provide more sophisticated load-balancing options than round-robin, and they keep track of failed servers to avoid routing unnecessary requests.

9)How many WebLogic Servers can I have on a multi-cpu machine?

There are many possible configurations and each has its own advantages and disadvantages. BEA WebLogic Server has no built-in limit for the number of server instances that can reside in a cluster. Large, multi-processor servers such as Sun Microsystems, Inc. Sun Enterprise 10000, therefore, can host very large clusters or multiple clusters. In most cases, WebLogic Server clusters scale best when deployed with one WebLogic Server instance for every two CPUs. However, as with all capacity planning, you should test the actual deployment with your target web applications to determine the optimal number and distribution of server instances.

10)How can I set deployment order for applications?

WebLogic Server allows you to select the load order for applications. WebLogic Server deploys server-level resources (first JDBC and then JMS) before deploying applications. Applications are deployed in this order: connectors, then EJBs, then Web Applications. If the application is an EAR, the individual components are loaded in the order in which they are declared in the application.xml deployment descriptor.

11)Can I refresh static components of a deployed application without having to
redeploy the entire application?

Yes. You can use weblogic.Deployer to specify a component and target a server, using the following syntax:

java weblogic.Deployer -adminurl http://admin:7001 -name appname -targets server1,server2 -deploy jsps/*.jsp

12)When should I use the -nostage option?

Set the staging mode to -nostage (using weblogic.Deployer or the Administration Console) if you don’t want to copy deployment files but want to deploy an application from its present location. All target servers must be able to access the same set of deployment files.

13)When should I use the external_stage option?

Set -external_stage using weblogic.Deployer if you want to stage the application yourself, and prefer to copy it to its target by your own means.

14)Can I set the deployment order for application modules? For standalone
modules?

The Load Order attribute controls the deployment order of standalone modules and applications relative to other modules and applications of the same type. For example, standalone EJBs with smaller Load Order values are deployed before those with higher values. Modules that are deployed as part of an Enterprise Application (EAR file or directory) are deployed in the order in which they are specified in the application.xml deployment descriptor. What is the difference between the WL_HOME/config/examples/applications folder and the WL_HOME/config/examples/stage folder? The applications folder is intended for applications that are not yet ready for a production environment. WebLogic Server dynamically deploys the contents of the applications folder. The stage folder (or a folder that you create for the same purpose) is for storing copies of deployment files that are ready for deployment in a production environment (deployments that use the stage or external_stage deployment modes).

15)How do I turn the auto-deployment feature off?

The auto-deployment feature checks the applications folder every three seconds to determine whether there are any new applications or any changes to existing applications and then dynamically deploys these changes. The auto-deployment feature is enabled for servers that run in development mode. To disable auto-deployment feature, use one of the following methods to place servers in production mode:

* In the Administration Console, click the name of the domain in the left pane, then select the Production Mode checkbox in the right pane.

* At the command line, include the following argument when starting the domain’s Administration Server: -Dweblogic.ProductionModeEnabled=true

Production mode is set for all WebLogic Server instances in a given domain.

16)Must EJBs be homogeneously deployed across a cluster? Why?

Yes. In WebLogic Server 6.0 and later, EJBs must be homogeneously deployed across a cluster for the following reasons:

* To keep clustering EJBs simple

* To improve performance by avoiding cross-server calls. If EJBs are not deployed on all servers, cross-server calls are more likely.

* To ensure that every EJB is available locall.y

* To ensure that all classes are loaded in an undeployable way. Every server must have access to each EJB’s classes so that it can be bound into the local JNDI tree. If only a subset of the servers deploys the bean, the other servers will have to load the bean’s classes in their respective system classpaths which makes it impossible to undeploy the beans.

Filed Under: Interview Questions Tagged With: WebLogic

JBoss Seam Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

Q: What version of JBoss AS do I need to run Seam?

A: For Seam 1.3: Seam was developed against JBoss 4.2. Seam can still be run against JBoss 4.0. The seam documentation contains instructions for configuring JBoss 4.0.

A: For Seam 1.2: Since Seam requires the latest edition of EJB3, you need to install JBoss AS from the latest JEMS installer. Make sure that you select the “ejb3” or “ejb3+clustering” profile to include EJB3 support. Also, the jboss-seam.jar library file from the Seam distribution must be included in each Seam application you deploy. Refer to examples in Seam distribution (inside the examples directory) to see how to build and package Seam applications.

Q: Can I run Seam outside of JBoss AS?

A: Yes, you can run Seam applications in plain Tomcat 5.5+ or in the Sun GlassFish application server. To run Seam application in Tomcat, you need a number of additional library files and a few configuration files to bootstrap the JBoss EJB3 inside Tomcat. Please refer to the deploy.tomcat ANT build target for the Seam booking example (in the examples/booking directory of the Seam distribution) for more on how to build a Tomcat WAR for Seam applications. Refer to this blog post on how to run Seam in Sun’s Glassfish application server.

Q: Can I run Seam in a J2EE environment?

A: Yes, as of Seam 1.1, you can use Seam in any J2EE application server, with one caveat: you will not be able to use EJB 3.0 session beans. However, you can use either Hibernate or JPA for persistence, and you can use Seam JavaBean components instead of session beans.

Q: Can I run Seam with JDK 1.4 and earlier?

A: No, Seam only works on JDK 5.0 and above. It uses annotations and other JDK 5.0 features.

Q: Where can I find Seam examples and documentation?

A: The source code and build script of all Seam example applications are included in the examples directory of the Seam distribution. Seam documentation is available here.

Q: Where can I ask questions and make suggestions about Seam?

Please use the Seam User’s discussion forum for user questions.

Q: Are there books about Seam?

A: Yes, Prentice Hall’s “JBoss Seam: Simplicity and Power Beyond Java EE 5.0” is a comprehensive guide for Seam written by JBoss insiders.

Q: Is it true that Seam only works with JSF?

Seam only supports JSF as a view framework at this time. We plan to support other web rameworks in the future. We like JSF because it is a component-based UI framework, which fits really well with Seam’s component-based approach to business objects and persistence objects. Seam made a major improvement to JSF by eliminating almost all XML configuration for backing beans — you can now define back beans from POJOs or EJB3 components using simple annotations. We recommend you use Facelets, instead of JSP, with JSF. Facelets provide a powerful templating framework, better appplication performance, and allows us to write much simpler JSF pages. Please see the Seam booking example application for an example on how to use Facelets.

Q: Can I use AJAX with Seam?

A: Yes, Seam provides excellent support for AJAX. First, Seam supports the ICEfaces and Ajax4JSF Ajax component libraries for JSF. If you prefer a more “old fashioned” approach, Seam provides a complete JavaScript remoting framework which lets you call Seam components and subscribe to JMS topics directly from the client. Please refer to the Seam remoting example application on how to use AJAX remoting to implement a chat room.

Finally, Seam’s concurrency model is designed especially for use with Ajax.

Q: Can I unit test Seam applications without starting the Application Server?

Yes, Seam provides its own integration test framework based on TestNG. You can easily mock all Seam services using those facilities without ever loading an application server or a database. Refer to the testexample ANT target in the Seam booking example application for more details.

Q: What’s so special about Seam’s “state management”?

A: Most other web frameworks store all application state in the HTTP session, which is inflexible, difficult to manage and a major source of memory leak. Seam can manage business and persistence components in several stateful scopes: components that only need to live across several pages are placed in the conversation scope; components that need to live with the current user session are placed in the session scope; components that require interactions from multiple users and last extended period of time (i.e., survive server reboots) are placed in the business process scope. The advanced state management facilities allow us to develop web application features that are previously not possible, or very difficult, to implement.

Q: Does Seam support multiple browser windows or tabs?

A: Yes. Seam supports fine-grained user state management beyond the simple HTTP session. It isolates and manages user state associated with individual browser window or tab (in contrast, HTTP session is shared across all windows of the same browser). So, in a Seam application, each browser window / tab can become a separate workspace that has independent history and context. Multiple user “conversations” can be supported for the same browser. This behavior is similar to that in rich client applications. To see this feature in action, just run the booking example application and try to book several hotels via several browser tabs in parallel — you can see that each tabs retains its own progress in the booking conversation.

Q: Can Seam handle back-button navigation?

A: Seam’s nested conversation model makes it really easy to build complex, stateful applications that tolerate use of the back button.

Q: Does Seam support REST style bookmarkable URLs?

A: Yes, it is very easy to expose REST style bookmarkable URLs in a Seam application. In addition, the Seam application can initialize all the necessary backend business logic and persistence components when the user loads that URL. This way, the RESTful URL is not only an information endpoint but also an application interaction start point.

Q: I heard Seam conversations are propagated through JSF POST request. Can I do redirect-after-post or even GET in the same conversation?

A: Yes, on both accounts! To use redirect-after-post, you just need to enable the SeamRedirectFilter in web.xml. To propagate a conversation through a GET request, pass the conversation id in a request parameter named conversationId. By default, GET (non-faces) requests always occur in a new conversation.

Q: Can I use Seam in a portal?

A: Seam 1.0 features full integration with JSR-168 compliant portals such as JBoss Portal.

Q: Does Seam have something like the Ruby on Rails “flash” object?

A: No, Seam has something much more powerful: a conversation context. The Seam conversation context is propagated across redirects (even when no long-running conversation is in progress), so you can use the conversation context to store success messages and the like.

Q: Does Seam have continuations?

A: A jBPM “wait state” is a continuation. Each node in a pageflow definition or node in a business process definition is a jBPM wait state. Speaking more approximately, you might like to think of the conversation state as a continuation. (We do not usually talk in this kind of language because it is too mysterious-sounding and obfuscates simple concepts to make them seem more impressive.)

Q: Does Seam support internationalization?

A: Seam includes several extensions to JSF that make it super-easy and super-elegant to create internationalized user interfaces.

Q: Are there any development tools that support Seam?

A: Seam 1.1 includes a Ruby on Rails style command line tool that makes it easy to set up a new Seam project, create some simple actions, and even reverse engineer a data driven application from an existing database.

IDE integration is also a major focus for us. JBoss Eclipse IDE provides a sophisticated, template-driven database reverse engineering tool which can generate an entire Seam application in minutes and a graphical jPDL editor for editing Seam pageflows and workflow definitions. More to come, stay tuned.

Filed Under: Interview Questions Tagged With: JBoss Seam

JVM,JRE,Java Compiler Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

JVM,JRE,Java Compiler FAQs-1

1)How can I write a program that takes command line input?

A: Java programs that take input from the command line declare a special static method called main, which takes a String array as an argument and returns void. The example program below loops through any arguments passed to the program on the command line and lists their values.

2)What does public static void main(String[]) mean?

A: This is a special static method signature that is used to run Java programs from a command line interface (CLI). There is nothing special about the method itself, it is a standard Java method, but the Java interpreter is designed to call this method when a class reference is given on the command line, as below.

3)Why are command line arguments passed as a String?

A: Command line arguments are passed to the application’s main method by the Java runtime system before the application class or any supporting objects are instantiated. It would be much more complex to define and construct arbitrary object types to pass to the main method and primitive values alone are not versatile enough to provide the range of input data that strings can. String arguments can be parsed for primitive values and can also be used for arbitrary text input, file and URL references.

4)Why doesn’t the main method throw an error with no arguments?

A: When you invoke the Java Virtual Machine on a class without any arguments, the class’ main method receives a String array of zero length. Thus, the method signature is fulfilled. Provided the main method does not make any reference to elements in the array, or checks the array length before doing so, no exception will occur.

5)Why do we only use the main method to start a program?

A: The entry point method main is used to the provide a standard convention for starting Java programs. The choice of the method name is somewhat arbitrary, but is partly designed to avoid clashes with the Thread start() and Runnable run() methods, for example.

6)Can the main method be overloaded?

A: Yes, any Java method can be overloaded, provided there is no final method with the same signature already. The Java interpreter will only invoke the standard entry point signature for the main method, with a string array argument, but your application can call its own main method as required.

7)Can the main method be declared final?

A: Yes, the static void main(String[]) method can be declared final.

8)I get an exception if I remove the static modifier from main!

A: The static void main(String[]) method is a basic convention of the Java programming language that provides an entry point into the runtime system. The main method must be declared static because no objects exist when you first invoke the Java Virtual Machine (JVM), so there are no references to instance methods. The JVM creates the initial runtime environment in which this static method can be called, if you remove the static modifier, it will throw a NoSuchMethodException.

9)How can the static main method use instance variables?

A: For very simple programs it is possible to write a main method that only uses static variables and methods. For more complex systems, the main method is used to create an instance of itself, or another primary class, as the basis of the application. The primary application object reference uses instance methods to create and interact with other objects, do the work and return when the application terminates.

[code lang=”java”]public class SimpleClass {

public void doSomething() {

// Instance method statements
}

public static main(final String[] args) {

SimpleClass instance = new SimpleClass();

instance.doSomething();
}
}[/code]

10)main method from another class?

A: Yes, the main method can be called from a separate class. First you must prepare the string array of arguments to pass to the method, then call the method through a static reference to the host class, MaxFactors in the example below.

[code lang=”java”]String[] arguments = new String[] {"123"};

MaxFactors.main(arguments);
[/code]

11)What is the source code for the compiler?

A: The source code for a Java program is also known as a compilation unit, which contains the code for a top level Java class or interface. A Java compilation unit is usually created in the form of a file with a .java extension and is passed to the compiler as a file path reference.

The Java source file contains a header that declares the type of class or interface, its “visibility” with respect to other classes, its name and any superclass it may extend, or interface it implements. The body of the class contains variable declarations and methods that define the behaviour of the class, and any constructors used to create an instance of the class. A compilation unit may also contain nested inner classes.

12)Why is the source file named after the class?

A: The Java source file naming convention is not a standard specified by the Java language but is a common feature of Java compilers, such as javac, to help locate source code. The source content of a Java class is known as a compilation unit. By storing the compilation unit in a file that is named after the class, the compiler can locate any supporting classes by name and compile those too.

This convention also extends to package names. Most Java compilers expect source code to be stored in directories whose names match their package hierarchy. Thus the source code for a class named Example in the package com.domain.util might be stored in a file with the path c:\src\com\domain\util\Example.java

13)Which class should be compiled first?

A: Sometimes you will find that trial and error will give you the answer you need. If you are using the Sun compiler, javac, the compiler will compile any other classes that your target class depends on, provided the other source files are in the same directory hierarchy as the first and the sub-directory names reflect the package hierarchy of the classes.

14)What are the steps in compiling a class?

Once you have written the Java source code file, there is only one step required to compile it. To compile the class from the command line, you need to give the path to the compiler program, such as Sun javac, and the path of the source code file, like this:

15)Where is my compiled class file?

A: If you are sure your class is being compiled, then the class file should be output somewhere! Without any directory argument, your compiler should place the class file in the same directory as your source file. Use the output directory argument to specify where the class files are generated.

16)How can I ensure my compiler will locate the SAX package?

A: One way to ensure your compiler can locate any package it may require is to pass its path to the compiler explicitly using the -classpath argument.

17)What does this deprecation message mean?

A: The deprecation message you have seen means that the methods you are calling have been marked with a JavaDoc deprecation comment. When a method or class is marked deprecated it is only advisory, not mandatory, but the advice is given for good reason and should be followed. So long as deprecated methods remain in the public API it is possible to use them, so this approach supports legacy code and gives developers time to amend their applications as necessary.

18)What are undefined and undeclared variables?

A: One gets warning messages about undefined and undeclared variables when compiling Java classes that have programming errors, as in the example below.

19)Why doesn’t the compiler warn about stack overflow problems?

A: There are many cases of poor runtime programming that could potentially be identified at compile time, but the number and subtlety of the cases gets increasingly difficult to address. The main purpose of a compiler is to produce executable byte code that is valid according to the rules of the programming language, not to guard against poor programming. Hence most compilers only validate the syntax of the language and the most obvious logical errors in the code at compile time.

20)How do I set environment variables on Windows XP?

A: For Windows 2000/XP systems, the environment settings are edited in a special Control Panel applet called System.

21)How do I set the compiler path?

A: The Java compiler is a program like any other and your operating system needs to know where to find the executable file. The simplest way to do this is to give the full path to the Java compiler in the command, as below for Windows…

22)How do I configure EditPlus to compile Java and capture output?

A: These instructions on configuring the NSGMLS markup validator for EditPlus will help you get started. For Java, the Command field will be the path to your javac.exe program (or java.exe to run). The Argument should contain any parameters you want to pass to the compiler and should end with the $(FilePath) variable that substitutes the current file name. Check the Capture output box to get feedback from the compiler.

Filed Under: Interview Questions Tagged With: JRE, JVM

Tapestry Interview Questions and FAQs

August 5, 2010 by Krishna Srinivasan Leave a Comment

Jakarta Tapestry Interview Questions and FAQs – 1

1. How does Tapestry compare to other frameworks?

Tapestry is very much unlike most other frameworks in that it doesn’t use code generation; instead it uses a true component object model based on JavaBeans properties and strong specifications. This gives Tapestry a huge amount of flexibility and enables dynamic runtime inspection of the application with the Tapestry Inspector (a mini-application that can be built into any Tapestry application).

In addition, Tapestry applications require far less Java coding and are far more robust than equivalent applications developed with other popular frameworks. This is because the Tapestry framework takes responsibility for many important tasks, such as maintaining server-side state and dispatching incoming requests to appropriate objects and methods.

The many new features of release 3.0 mean that Tapestry is not only the most powerful web application framework available, it is also the fastest and easiest to adopt, regardless of whether your background is Java, Perl, XML or PHP!

2. How is the performance of Tapestry?

My own testing, documented in the Sept. 2001 issue of the Java Report, agrees with other testing (documented in the Tapestry discussion forums): Although straight JSPs have a slight edge in demo applications, in real applications with a database or application server backend, the performance curves for equivalent Tapestry and JSP applications are identical.

Don’t think about the performance of Tapestry; think about the performance of your Java developers.

3. Is Tapestry a JSP tag library?

Tapestry is not a JSP tag library; Tapestry builds on the servlet API, but doesn’t use JSPs in any way. It uses it own HTML template format and its own rendering engine.

Starting with release 3.0, Tapestry includes a simple JSP tag library to allow JSP pages to create links to Tapestry pages.

4. What does it cost?

Tapestry is open source and free. It is licensed under the Apache Software License, which allows it to be used even inside proprietary software.

5. Is there a WYSIWYG editor for Tapestry, or an IDE plugin?

Currently, no WYSIWYG editor is available for Tapestry; however, the design of Tapestry allows existing editors to work reasonably well (Tapestry additions to the HTML markup are virtually invisible to a WYSIWYG editor).

Spindle is a Tapestry plugin for the excellent open-source Eclipse IDE. It adds wizards and editors for creating Tapestry applications, pages and components.

6. Does Tapestry work with other other application servers besides JBoss?

Of course! JBoss is free and convenient for the turn-key demonstrations. You can download Tapestry and JBoss and have a real J2EE application running in about a minute! The scripts that configure JBoss are sensitive to the particular release of JBoss, it must be release 3.0.6.

However, Tapestry applications are 100% container agnostic … Tapestry doesn’t care what servlet container it is used with and does not even require an EJB container.

7. How do I integrate a Tapestry application with J2EE declarative
security/JAAS?

In web.xml:

add an additional servlet mapping for your tapestry application to /admin, and add the following:
[code lang=”xml”]<security-constraint>
<web-resource-collection>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
[/code]
In your base class for protected pages:
[code lang=”java”]public void validate(IRequestCycle cycle) throws RequestCycleException {

boolean isAdmin = getRequestCycle().getRequestContext().getRequest().isUserInRole("ADMIN");
if (!isAdmin) {
// not in right role
throw new PageRedirectException…….
}

}
[/code]
you can have a number of mappings for the same app-servlet to different URIs, that way you can rely a bit more on the declarative security.. not perfect, but works.. 🙂 ViktorSzathmary

8. How do I Write Components?

  1. Retrieving bound properties : When writting a component, you often require various properties to be supplied by the component user. At some point during rendering, you will want to use the value of this property.

    You can do this by accessing the Binding. Assume we have a component with one property called ‘values’. Our component will use this list in its preRenderCommponent() method to setup some model, for use elsewhere.
    [code lang=”java”]…. if(getValues() == null) {

    IBinding binding = getBindings("values"); if(binding.getObject() == null) {

    throw new RequestCycleException("The value for ‘values’ cannot be null", this);

    } setValues((List)values.getObject());

    }
    [/code]
    The binding itself will ensure that the object value is the correct type (assuming of course, it’s been setup right).

  2. Performing Lazy Instantiation of state based upon component properties : In some cases, the output of a component may be based upon the state of some other property of the same component. For example, imagine a form where the user can choose the type of product to view. When they choose a product, the form makes a query to the database for products matching this type, and reshows the list on the same page. (the list would be included outside of the form element itself).

    Lets assume that the page object exposes it’s products via a getProductModel() – which is an instance of IPropertySelectionModel.

    We will also assume that the remainder of the page has the other components necessary to render correct HTML, using the value supplied by the getProductModel() result.

    Here, it is helpful to know when in the rendering process you can rely on the value of selectedProduct to be set correctly, so that you can instantiate a ProductModel based on the provided value, for use in the form rendering. The best place to setup state is in the preRenderComponent() method. This is called by Tapestry just before it renders any component, but AFTER it has set component properties. So, we might write:
    [code lang=”java”]protected void preRenderComponent() {

    String selected = getSelectedProduct();
    List products = getMatchingProducts(selectedProduct);
    productModel = new ProductModel(products);
    .. other initialization code …

    }[/code]

9. @Script – Why is it needed and how does it work?

IMO, the script framework is an effective means to bundle scripts in components. It provides scripts with the advantages of components. It can now be reused like a component and not have to worry about renaming field names or the wiring between the fields and the scripts. You just declare the component and you are good to go. It certainly is another layer of abstraction that one will have to learn but once you have learned it, it is very powerful. And honestly there is not much to it.

The script framework is mandated by the fact that form element/field names are automatically generated by the framework. And so you write your script in XML and use variables for these names and let the framework provide the correct names during runtime. Going further, you may also ask the framework to provide other objects that would help in creating your script. For example…
[code lang=”xml”]<input-symbol key="select"
class="org.apache.tapestry.form.PropertySelection"
required="yes"/>
[/code]
This defines an input variable “select” of type “org.apache.tapestry.form.PropertySelection”. All such variables/symbols passed in to the script is stored in a symbol map. And now you can use the form select list name by using an ant style syntax like ${select.name}. The expression within “${}” is an OGNL expression and is evaluated with respect to the symbol map. You may also define your own symbols/variables using
<let…> like…
[code lang=”xml”]<let key="formObj">

document.${select.form.name}

</let>
<let key="selectObj">

${formObj}.${select.name}

</let>
[/code]
These variables/symbols are stored in the symbol map also. So now if you want to set the value of the form select list all you do is say ${formObj}.${selectObj}.value = ‘whatever’; this would be equivalent to document.myForm.mySelect.value = ‘whatever’; where myForm is the form name and mySelect is the select list name.
[code lang=”xml”]<input-symbol…>s are like method parameters and <let…>s are like instance variables. Typically you would pass values to the <input-symbol…>s via the Script component like…

<component id="myScript" type="Script">

<static-binding name="script" value="ScriptSpecificationName.script"/>
<binding name="select" expression="components.somePropertySelection"/>

</component>
[/code]
The actual scripts are defined in one of the two sections of the script specification, <body…> or <initialization…>, depending on when you want the script to execute. If you want the script to execute on load of the page, then you define it in the <initialization…>, if you want it to execute on any other event, define it in the <body…> section of the specification. For example…
[code lang=”xml”]<body>

function onChangeList(listObj)
{

alert(listObj.value);

}

</body>

<initialization>

${selectObj}.onchange = function(e)
{

onChangeList(${selectObj});

}

</initialization>
[/code]
As you can see in the rendered page all scripts are aggregated at the top of the page body, there are no more scripts all over the page. Even event handlers are attached to form objects in the initialization block.

One more thing to remember, scripts being components, and components by nature being independent of its environment, will render the script in the page once for every ocurrance of the component. If you want the body of the script to be rendered only once no matter how many times the component is used, just wrap the body in a <unique> tag like…
[code lang=”xml”]<body>
<unique>

function onChangeList(listObj)
{

alert(listObj.value);

}

</unique>
</body>
[/code]
That’s all there is to it!

* HarishKrishnaswamy

10. cycle.activate() does not seem to alter the URL. Is there any alternative that will alter the URL to point to the correct page?

You would need to throw a RedirectException with the new URL; this sends an HTTP redirect to the client.

11. How do I do page navigation like struts?

Usage page properties:
Page1.page
[code lang=”xml”]
<page-specification class="xyz.Action">
…
<property name="success" value="Home" />
<property name="error" value="Error" />

</page-specification>[/code]

Page2.page
[code lang=”xml”]<page-specification class="xyz.Action">
…
<property name="success" value="Home2" />
<property name="error" value="Error2" />

</page-specification>

xyz.Action.java
…
public void submitListener(IRequestCycle cycle)
{
if (success)
cycle.activate(getSpecification().getProperty("success"));

if (error)
cycle.activate(getSpecification().getProperty("error"));
}[/code]
— Tip from Harish

12. How do I make a link popup a new window?

Use the contrib:PopupLink component.

13. How do I stream a file to the user from tapestry?

Make a method like the following a a listener, such as from a DirectLink or whatever.

(The Document is just a class that holds the file information you want to send to the user.)
[code lang=”java”]public void downloadAction(IRequestCycle cycle)
{
try
{
HttpServletResponse response =
cycle.getRequestContext().getResponse();

byte[] data = new byte[1024];
FileInputStream in = document.getFileInputstream();

response.setHeader("Content-disposition",
"inline; filename=" +
document.getFileName());
response.setContentType(document.getMimeType());
response.setContentLength(new Long(document.getSize()).intValue());
ServletOutputStream out = response.getOutputStream();

while (in.read(data) > -1)
{
out.write(data);
}
in.close();
response.flushBuffer();
}
catch (IOException e)
{
e.printStackTrace();
}
}
[/code]

14. I need to calculate a URL to jump to a particular page. How do I do this?

The best bet is to use the external service. This lets you directly invoke a page and pass objects as parameters. The page you want to jump to will need to implement IExternalPage. To calculate the URL you have to use something like this:
[code lang=”java”]cycle.getEngine()
.getService( Tapestry.EXTERNAL_SERVICE )
.getLink( cycle, cycle.getPage(), new Object[]{
"MyPageName",
param1,
param2} )
.getURL()
[/code]

15. I have a form with a submit button. On the form and the submit button are two separate listeners. Which is invoked first?

The button’s listener should get invoked when the form encounters your button during the rewind. the form’s submitListener should get invoked after the form has completed its rewind, and thus after all other listeners have been invoked. note – this can mean that the listener for a button can be invoked BEFORE the form has ‘submitted’ all its values – it depends where your input fields are relative to your button.

16. I’d like to be able attach my own client-side javascript handling on the form submit. What’s the best way to do this?

You can add event handler during component rendering:
[code lang=”java”]protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle){
…
yourFormComponent.addEventHandler(FormEventType.SUBMIT, "javaScriptValidatingFunctionName");
…
}
[/code]
org.apache.tapestry.contrib.palette.Palette can be used for detailed example.

17. What’s the lifecycle of a form submit?

Events will trigger in the following order:
[code lang=”java”]initialize()
pageBeginRender()
formListenerMethod()
pageBeginRender()
[/code]
The form “rewind” cycle is nothing more than a render cycle where the output is buffered and scrapped rather than written to the servlet output stream. The second pageBeginRender() is triggered during the actual page rendering. You can use requestCycle.isRewinding() to distinguish between these two render cycles.

18. Can I use the same component multiple times in one template?

No – but you can copy the definition of a component pretty easily.
[code lang=”xml”]<component id="valueInsert" type="Insert" >
<binding name="value" expression="getValueAt( rowIndex, columnIndex )" />
</component>

<component id="valueInsert1" copy-of="valueInsert"/>
<component id="valueInsert2" copy-of="valueInsert"/>
<component id="valueInsert3" copy-of="valueInsert"/>
<component id="valueInsert4" copy-of="valueInsert"/>
[/code]

19. I have to restart my application to pick up changes to specifications and templates, how can I avoid this?

Start your servlet container with the JVM system parameter org.apache.tapestry.disable-caching set to true, i.e., -Dorg.apache.tapestry.disable-caching=true.

Tapestry will discard cached specifications and templates after each request. You application will run a bit slower, but changes to templates and specifications will show up immediately. This also tests that you are persisting server-side state correctly.

Filed Under: Interview Questions Tagged With: Tapestry

Java Threads Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

Java Threads Interview Questions – 1

1)What is threaded programming and when is it used?

Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.
The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications.

2)Why are wait(), notify() and notifyall() methods defined in the Object class?

A: These methods are detailed on the Java Software Development Kit JavaDoc page for the Object class, they are to implement threaded programming for all subclasses of Object.

3)Why are there separate wait and sleep methods?

A: The static Thread.sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up control over thread execution indefinitely so that other threads can run.

4) What’s the difference between Thread and Runnable types?

A: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it.
The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

5)How does the run() method in Runnable work?

A: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects.

6)A Thread is runnable, how does that work?

A: The Thread class’ run method normally invokes the run method of the Runnable type it is passed in its constructor. However, it is possible to override the thread’s run method with your own.

7)Why not override Thread to make a Runnable?

A: There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited.
Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

8)What’s the difference between a thread’s start() and run() methods?

A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.
The Thread class’ run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread’s run() method executes the run() method of the Runnable object in the new thread instead.
Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

9)Can I implement my own start() method?

A: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.

10)Do I need to use synchronized on setValue(int)?

A: It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues.

11)How do I create a Runnable with inheritance?

A: To introduce a Runnable type to an existing class hierarchy, you need to create a sub-class that declares that it implements the Runnable interface, and provide a run method to fullfil the interface. This combination of interface and inheritance means that runnable implementations can be very minor extensions of existing classes, as in the example below…

12)What is the SwingUtilities.invokeLater(Runnable) method for?

A: The static utility method invokeLater(Runnable) is intended to execute a new runnable thread from a Swing application without disturbing the normal sequence of event dispatching from the Graphical User Interface (GUI). The method places the runnable object in the queue of Abstract Windowing Toolkit (AWT) events that are due to be processed and returns immediately. The runnable object’s run() method is only called when it reaches the front of the queue.
The deferred effect of the invokeLater(Runnable) method ensures that any necessary updates to the user interface can occur immediately, and the runnable work will begin as soon as those high priority events are dealt with. The invoke later method might be used to start work in response to a button click that also requires a significant change to the user interface, perhaps to restrict other activities, while the runnable thread executes.

13)What is the volatile modifier for?

A: The volatile modifier is used to identify variables whose values should not be optimized by the Java Virtual Machine, by caching the value for example. The volatile modifier is typically used for variables that may be accessed or modified by numerous independent threads and signifies that the value may change without synchronization.

14)Which class is the wait() method defined in?

A: The wait() method is defined in the Object class, which is the ultimate superclass of all others. So the Thread class and any Runnable implementation inherit this method from Object. The wait() method is normally called on an object in a multi-threaded program to allow other threads to run. The method should should only be called by a thread that has ownership of the object’s monitor, which usually means it is in a synchronized method or statement block.

15)What is a green thread?

A: A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads.
There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Current JVM implementations make more efficient use of native operating system threads.

16)What is a working thread?

A: A working thread, more commonly known as a worker thread is the key part of a design pattern that allocates one thread to execute one task. When the task is complete, the thread may return to a thread pool for later use. In this scheme a thread may execute arbitrary tasks, which are passed in the form of a Runnable method argument, typically execute(Runnable). The runnable tasks are usually stored in a queue until a thread host is available to run them.
The worker thread design pattern is usually used to handle many concurrent tasks where it is not important which finishes first and no single task needs to be coordinated with another. The task queue controls how many threads run concurrently to improve the overall performance of the system. However, a worker thread framework requires relatively complex programming to set up, so should not be used where simpler threading techniques can achieve similar results.

Filed Under: Interview Questions Tagged With: Java

Groovy Interview Questions and FAQs

August 5, 2010 by Krishna Srinivasan Leave a Comment

Groovy Interview Questions and FAQs – 1

What is Groovy?

Groovy is a powerful high level language for the Java platform which compiles down to Java bytecode.
Think of it as a Ruby or Python like language that is tightly integrated with the Java platform – allowing you the same powerful and concise coding syntax as Ruby or Pyton but allowing you to stay on the JVM and protect your investment in J2SE, J2EE and all the plethora of great useful Java code out there.

Why Groovy? Why don’t you just use Jython, JRuby, bsh, rhino, pnuts, …

Firstly ports of existing languages like Python, Ruby, Smalltalk and JavaScript to the JVM are a good thing and we welcome them. If you already use and/or are fond of these languages please be our guests to use the Java-port of them.One of the main design goals of Groovy is to be a scripting language for Java developers to use. So we wanted to reuse both Java’s semantics and the whole set of J2SE APIs rather than introduce a port of a different language with different semantics and APIs to learn and implement/maintain.

e.g. in Groovy, java.lang.Object is the root of the object hierarchy, Object.equals(), Object.hashCode() and Comparable are used for comparions and lookups of objects, that java.util.List and java.util.Map are used for collections, Java Beans are fully supported and that Java and Groovy classes are interchangable inside the VM. Groovy is built on top of the J2SE APIs, rather than having 2 parallel platforms etc.
In other words we wanted the Groovy language to be very easy to pick up if you’re already a Java developer and for there to be a very small number of new APIs to learn. By this statement we’re not implying that Python / Ruby / JavaScript are hard to learn per se – its just there’s more to know, things are more different and there’s more APIs to learn

Think of Groovy as a Ruby or Python like language that is tightly integrated with the Java platform (as opposed to the Unix/Posix command shell and C-libraries) – allowing you the same powerful and concise coding syntax as Ruby or Pyton but allowing you to stay on the JVM and protect your investment in J2SE, J2EE and all the plethora of great useful Java code out there without any adapter layers or parallel API sets etc. There is a more detailed set of comparisio ther languages here

What are the dependencies for Groovy?

As well as Java 1.4 and the Groovy jar we also depend at runtime on the ASM library.

What is the licence for Groovy?

Groovy is open source using a BSD / Apache style licence

I get errors when trying to run groovy, groovysh or groovyConsole. Whats wrong?

Groovy depends on JDK 1.4 or later. Common errors people have when trying to run Groovy is that there’s an old groovy jar on the CLASSPATH somewhere (have you checked in java/lib/ext?) or that JAVA_HOME points to an old JDK before JDK 1. For more help please see this description of running Groovy code.

How can I add stuff to the classpath when running things in groovysh or groovy?

You can add things to your $CLASSPATH environment variable. Another popular option is to create a .groovy/lib directory in your home directory and add whatever jars you want to be available by default. e.g. if you wish to connect to your favourite JDBC database and do some scripting with it then add your JDBC driver to ~/.groovy/lib.

Things work if I use Suns conventions and put { on the same line, but if I add a new line things break?

When using closures with method calls we have some syntax sugar in Groovy which is sensitive to white space (newlines to be precise). Please see this description in common gotchas for a full description.

Filed Under: Interview Questions Tagged With: Groovy

Tomcat Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

Tomcat Interview Questions – 1

How do you create multiple virtual hosts?

If you want tomcat to accept requests for different hosts e.g., www.myhostname.com then you must 0. create ${catalina.home}/www/appBase , ${catalina.home}/www/deploy, and ${catalina.home}/conf/Catalina/www.myhostname.com

  1. add a host entry in the server.xml file

    [code lang=”xml”] <Host appBase="www/appBase" name="www.myhostname.com"/>[/code]

  2. Create the the following file under conf/Catalina/www.myhostname.com/ROOT.xml

    [code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>
    <Context
    path="/"
    docBase="www/deploy/mywebapp.war"
    reloadable="true" antiJARLocking="true">
    </Context>[/code]

    Add any parameters specific to this hosts webapp to this context file

  3. put your war file in ${catalina.home}/www/deploy

    When tomcat starts, it finds the host entry, then looks for any context files and will start any apps with a context. To add more sites just repeat and rinse, all webapps can share the same war file location and appbase

How will you load properties file?

* Use a ResourceBundle. See the Java docs for the specifics of how the ResourceBundle class works. Using this method, the properties file must go into the WEB-INF/classes directory or in a jar file contained in the WEB-INF/lib directory.

* Another way is to use the method getResourceAsStream() from the ServletContext class. This allows you update the file without having to reload the webapp as required by the first method. Here is an example code snippet, without any error trapping:

[code lang=”java”]// Assuming you are in a Servlet extending HttpServlet
// This will look for a file called "/more/cowbell.properties" relative
// to your servlet Root Context
InputStream is = getServletContext().getResourceAsStream("/more/cowbell.properties");
Properties p = new Properties();
p.load(is);
is.close();[/code]

Can I set Java system properties differently for each webapp?

No. If you can edit Tomcat’s startup scripts, you can add “-D” options to Java. But there is no way to add such properties in web.xml or the webapp’s context.

How do I configure Tomcat to work with IIS and NTLM?

Follow the standard instructions for when the isapi_redirector.dll Configure IIS to use “integrated windows security”

In server.xml, make sure you disable tomcat authentication:
[code lang=”xml”]<Connector port="8009" enableLookups="false" redirectPort="8443" protocol="AJP/1.3" tomcatAuthentication="false" />[/code]

How can I access members of a custom Realm or Principal?

When you create a custom subclass of RealmBase or GenericPrincipal and attempt to use those classes in your webapp code, you’ll probably have problems with ClassCastException. This is because the instance returned by request.getUserPrincipal() is of a class loaded by the server’s classloader, and you are trying to access it through you webapp’s classloader. While the classes maybe otherwise exactly the same, different (sibling) classloaders makes them different classes.

This assumes you created a My“Principal class, and put in Tomcat’s server/classes (or lib) directory, as well as in your webapp’s webinf/classes (or lib) directory. Normally, you would put custom realm and principal classes in the server directory because they depend on other classes there.

Here’s what you would like to do, but it throws ClassCastException:

[code lang=”java”]MyPrincipal p = request.getUserPrincipal();
String emailAddress = p.getEmailAddress();[/code]

Here are 4 ways you might get around the classloader boundary:

  1. Reflection
    [code lang=”java”]
    Principal p = request.getUserPrincipal();
    String emailAddress = p.getClass().getMethod("getEmailAddress", null).invoke(p, null);[/code]
  2. Move classes to a common classloader

    You could put your custom classes in a classloader that is common to both the server and your webapp – e.g., either the “common” or bootstrap classloaders. To do this, however, you would also need to move the classes that your custom classes depend on up to the common classloader, and that seems like a bad idea, because there a many of them and they a core server classes.

  3. Common Interfaces
    Rather than move the implementing custom classes up, you could define interfaces for your customs classes, and put the interfaces in the common directory. You’re code would look like this:

    [code lang=”xml”]public interface MyPrincipalInterface extends java.security.Principal {
    public String getEmailAddress();
    }

    public class MyPrincipal implements MyPrincipalInterface {
    …
    public String getEmailAddress() {
    return emailAddress;
    }
    }

    public class MyServlet implements Servlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    MyPrincipalInterface p = (MyPrincipalInterface)request.getUserPrincipal();
    String emailAddress = p.getEmailAddress();
    …
    }[/code]

    Notice that this method gives you pretty much the webapp code you wanted in the first place

  4. Serializing / Deserializing
    You might want to try serializing the response of ‘request.getUserPrincipal()’ and deserialize it to an instance of [webapp]MyPrincipal.

How do I override the default home page loaded by Tomcat?

After successfully installing Tomcat, you usually test it by loading http://localhost:8080 . The contents of that page are compiled into the index_jsp servlet. The page even warns against modifying the index.jsp files for this reason. Luckily, it is quite easy to override that page. Inside $TOMCAT_HOME/conf/web.xml there is a section called <welcome-file-list> and it looks like this:

[code lang=”xml”]<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>[/code]
The default servlet attempts to load the index.* files in the order listed. You may easily override the index.jsp file by creating an index.html file at $TOMCAT_HOME/webapps/ROOT. It’s somewhat common for that file to contain a new static home page or a redirect to a servlet’s main page. A redirect would look
like:
[code lang=”html”]
<html>

<head>
<meta http-equiv="refresh" content="0;URL=http://mydomain.com/some/path/to/servlet/homepage/">
</head>

<body>
</body>

</html>
[/code]
This change takes effect immediately and does not require a restart of Tomcat.

How do I enable Server Side Includes (SSI)?

Two things have to be done for tomcat to aknowledge SSI scripts:

  1. Rename $CATALINA_BASE/server/lib/servlets-ssi.renametojar to $CATALINA_BASE/server/lib/servlets-ssi.jar.
  2. Uncomment the section of web.xml found in $CATALINA_BASE/conf/web.xml that deals with SSI. it looks like this when it is uncommented:

    [code lang=”xml”]
    <servlet>
    <servlet-name>ssi</servlet-name>
    <servlet-class>
    org.apache.catalina.ssi.SSIServlet
    </servlet-class>
    <init-param>
    <param-name>buffered</param-name>
    <param-value>1</param-value>
    </init-param>
    <init-param>
    <param-name>debug</param-name>
    <param-value>0</param-value>
    </init-param>
    <init-param>
    <param-name>expires</param-name>
    <param-value>666</param-value>
    </init-param>
    <init-param>
    <param-name>isVirtualWebappRelative</param-name>
    <param-value>0</param-value>
    </init-param>
    <load-on-startup>4</load-on-startup>
    </servlet>[/code]

How do I use DataSources with Tomcat?

When developing J2EE web applications, the task of database connection management can be daunting. Best practice involves using a J2EE DataSource to provide connection pooling, but configuring DataSources in web application servers and connecting your application to them is often a cumbersome process and poorly documented.

The usual procedure requires the application developer to set up a DataSource in the web application server, specifying the driver class, JDBC URL (connect string), username, password, and various pooling options. Then, the developer must reference the DataSource in his application’s web.xml configuration file, and then access it properly in his servlet or JSP. Particularly during
development, setting all of this up is tedious and error-prone.

With Tomcat 5.5, the process is vastly simplified. Tomcat allows you to configure DataSources for your J2EE web application in a context.xml file that is stored in your web application project. You don’t have to mess with configuring the DataSource separately in the Tomcat server.xml, or referencing it in your application’s web.xml file. Here’s how:

Install the JDBC Driver

Install the .jar file(s) containing the JDBC driver in Tomcat’s common/lib folder. You do not need to put them in your application’s WEB-INF/lib folder. When working with J2EE DataSources, the web application server manages connections for your application.

Create META-INF/context.xml

In the root of your web app directory structure, create a folder named META-INF (all caps). Inside that folder, create a file named context.xml that contains a Resource like this:

[code lang=”xml”]<?xml version="1.0" encoding="UTF-8"?>

<Context>

<Resource name="jdbc/WallyDB" auth="Container"
type="javax.sql.DataSource" username="wally" password="wally"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost;DatabaseName=mytest;SelectMethod=cursor;"
maxActive="8"
/>

</Context>[/code]

This example shows how to configure a DataSource for a SQL Server database named mytest located on the development machine. Simply edit the Resource name, driverClassName, username, password, and url to provide values appropriate for your JDBC driver.

Access the DataSource in Your Application

From a Servlet

Here’s how you might access the data in a servlet:

[code lang=”java”]InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/WallyDB");
Connection c = ds.getConnection();
…
c.close();[/code]
Notice that, when doing the DataSource lookup, you must prefix the JNDI name of the resource with java:comp/env/

Filed Under: Interview Questions Tagged With: Apache Tomcat

Apache Ant Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

Apache Ant Interview Questions – 1

1)What is ant?

Ant is a small animal who can build magnificent buildings. Ant builds! ANT is a Java based building tool, which is similar to make, and so much better than make. ANT, what a smart name for a building tool, even the original author of ANT, James Duncan Davidson, meant “Another Neat Tool”. A win-win ant learning method

There is a shortcut.

If you download a small jakarta project, such as Log4J, which is built by ant. It is a good and simple example for you to learn ant. Actually, you hit two birds with one stone.
Ant is easy!
The hard part is how to make a very complicated diversified system work very simple and elegant. Knowledge about ant is not enough, you need an elegant and simple design, you need great naming convention, you need to optimize the code reusability and flexibility, you need a least maintenance system…
Then it is not easy now ..

2)How do I get started to use ant? Can you give me a “Hello World” ant script?

Simple.

  • Download the most recent version of ant from Apache; unzip it some where on your machine.
  • Install j2sdk 1.4 or above.
  • Set JAVA_HOME and ANT_HOME to the directory your installed them respectively.
  • Put %JAVA_HOME%/bin;%ANT_HOME%/bin on your Path. Use ${JAVA_HOME}/bin:${ANT_HOME}/bin on UNIX. Yes, you can use forward slash on windows.
  • Write a “Hello world” build.xml

[code lang=”xml”]
<project name="hello" default="say.hello" basedir="." >
<property name="hello.msg" value="Hello, World!" />
<target name="say.hello" >
<echo>${hello.msg}</echo>
</target>
</project>[/code]

* Type ant in the directory your build.xml located.

* You are ready to go!!!!

3)How to delete files from a directory if it exists?

The following code fails when directory does not exist!

[code lang=”xml”]<delete>
<fileset dir="${upperdir.which.exists}">
<include name="${classes.dir}/*.class" />
</fileset>
</delete>[/code]

Your code has many problems.

  1. You should not use implicit fileset, which is deprecated. You should use nested fileset.
  2. If dir does not exist, the build will fail, period!
  3. If you are not sure, use a upper level dir, which exists for sure. See the following fileset.

[code lang=”xml”]<path id="build.classpath">
<fileset dir="${build.lib}" includes="**/*.jar"/>
<fileset dir="${build.classes}" />
</path>

<target….>
<javac ….>
<classpath refid="build.classpath" />
</java>
</target>

<target….>
<java ….>
<classpath refid="build.classpath" />
</java>
</target>[/code]

5)How does ant read properties? How to set my property system?

Ant sets properties by order, when something is set, the later same properties cannot overwrite the previous ones. This is opposite to your Java setters. This give us a good leverage of preset all properties in one place, and overwrite only the needed. Give you an example here. You need password for a task, but don’t want to share it with your team members, or not the developers outside your team.

Store your password in your ${user.home}/prj.properties

pswd=yourrealpassword

In your include directory master prj.properties

pswd=password

In your build-common.xml read properties files in this order

  1. The commandline will prevail, if you use it: ant -Dpswd=newpassword
  2. ${user.home}/prj.properties (personal)
  3. yourprojectdir/prj.properties (project team wise)
  4. your_master_include_directory/prj.properties (universal)

[code lang=”java”]<cvsnttask password="${pswd} … />[/code]

Problem solved!

6)How to modify properties in ant?

No, you can’t!

Properties in Ant are immutable. There is a good reason behind this, see this FAQ item for more details.

7)How to use ant-contrib tasks?

A: Simple, just copy ant-contrib.jar to your ant*/lib directory

And add this line into your ant script, all ant-contrib tasks are now available to you!
<taskdef
resource=”net/sf/antcontrib/antcontrib.properties” />

8)How to loop on a list or fileset?

Use ant-contrib <for> <foreach> tasks

General to say, use <for> is better than use <foreach> since for each is actually open another ant property space, use more memory too.

9)Why do I get en exception when I use location=”D:\\Code\\include” as
attribute of includepath?

See here.

You need to escape the string to “D:\\\\Code\\\\include” or use “D:/Code/include” instead!

Believe me or not? Forward slash works on windows in all ant or java code. It also works in windows environment variables. It does not work in cmd (dos) window before XP. It also works in XP dos window now!

10)Can I put the contents of a classpath or fileset into a property?

Yes, you can.

This is very similar to the call of Java class toString() method and actually it is calling the toString() method inside ant. For example

[code lang=”xml”]<fileset id="fs1" dir="t1" includes="**/*.java"/>
<property name="f1.contents" refid="fs1"/>
<echo>f1.contents=${f1.contents}</echo>[/code]

11)Where can I find the javadoc for ant API?

Download apache ant src version. Use ant javadocs command to see generated javadoc for ant in build/docs directory.

12)How can I use ant to run a Java application?

Here is a real world example.

[code lang=”xml”]<target name="run" depends="some.target,some.other.target">

<java classname="${run.class}" fork="yes">
<classpath>
<path refid="classpath" />
</classpath>

<jvmarg line="${debug.jvmargs}" />
<jvmarg line="${my.jvmargs}" />
<jvmarg value="-Dname=${name}" />
<jvmarg line="${run.jvmargs}" />
<arg line="${run.args}" />
</java>
</target>[/code]

13)How to use ant to run commandline command? How to get perl script running result?

Use exec ant task.

Don’t forget ant is pure Java. That is why ant is so useful, powerful and versatile. If you want ant receive unix command and result, you must think Unix. So does in MS-Windows. Ant just helps you to automate the process.

14)How do I debug my ant script?

Many ways

  • Do an echo on where you have doubt. You will find out what is the problem easily. Just like the old c printf() or Java System.println()
  • Use project.log(“msg”) in your javascript or custom ant task
  • Run Ant with -verbose, or even -debug, to get more information on what it is doing, and where. However, you might be tired with
    that pretty soon, since it give you too much information.

15)How to exclude multi directories in copy or delete task?

Here is an example.

[code lang=”xml”]<copy todir="${to.dir}" >
<fileset dir="${from.dir}" >
<exclude name="dirname1" />
<exclude name="dirname2" />
<exclude name="abc/whatever/dirname3" />
<exclude name="**/dirname4" />
</fileset>
</copy>[/code]

16)How to use Runtime in ant?

You don’t need to use Runtime etc. Ant have exec task.
The class name is org.apache.tools.ant.taskdefs.ExecTask. You can create the task by using the code in your customized ant Task.

ExecTask compile = (ExecTask)project.createTask(“exec”);

17)How to rearrange my directory structure in my jar/war/ear/zip file? Do I
need to unarchive them first?

No, you don’t need to unarchive them first.

  • You don’t need to unzip the files from archive to put into your destination jar/ear/war files.
  • You can use zipfileset in your jar/war/ear task to extract files from old archive to different directory in your new archive.
  • You also can use zipfileset in your jar/war/ear task to send files from local directory to different directory in your new archive.

See the follow example:
[code lang=”java”] <jar destfile="${dest}/my.jar">
<zipfileset src="old_archive.zip" includes="**/*.properties" prefix="dir_in_new_archive/prop"/>
<zipfileset dir="curr_dir/abc" prefix="new_dir_in_archive/xyz"/>
</jar>[/code]

18)Why did I get such warning in ant?

compile:

[javac] Warning: commons-logging.properties modified in the future.

[javac] Warning: dao\\DAO.java modified in the future.

[javac] Warning: dao\\DBDao2.java modified in the future.

[javac] Warning: dao\\HibernateBase.java modified in the future.

System time problem, possible reasons:

  • You changed the system time
  • I had the same problem before, I checked out files from cvs to windows, and transfer them to a unix machine, somehow, I got huge amount of such warnings because the system timing issue.
  • If you transfer files from Australia/China/india to the United States, you will get the problem too. True enough, I did and met the
    problem once.

19)How can I write my own ant task?

Easy!

Writing Your Own Task How-To from ant.
In your own $ANT_HOME/docs/manual directory, there also is tutorial-writing-tasks-src.zip

Use them! Use taskdef to define it in your script, define it before using it.

20)How to copy files without extention?

If files are in the directory:

[code lang=”xml”]<include name="a,b,c"/>[/code]

If files are in the directory or subdirectories:

[code lang=”xml”]<include name="**/a,**/b,**/c"/>[/code]

If you want all files without extension are in the directory or subdirectories:
[code lang=”xml”]<exclude name="**/*.*"/>[/code]

21)How do I use two different versions of jdk in ant script?

The followings are what I’m doing.

  1. Don’t define java.home by yourself. Ant uses an internal one derived from your environment var JAVA_HOME. It is immutable.
  2. I do the followings:

    * In my build.properties (read first)

    jdk13.bin=${tools.home}/jdk1.3.1_13/bin

    jdk14.bin=${tools.home}/j2sdk1.4.2_08/bin/

    * In my master properties file (read last), set default

    javac.location=${jdk13.bin}

    * In my prj.properties, if I need to use 1.4

    javac.location=${jdk14.bin}

    * in my javac task

    executable=”${javac.location}/javac.exe”

22)How to pass -Xlint or -Xlint:unchecked to 1.5 javac task?

pass it as compilerarg nested <compilerarg> to specify.

[code lang=”xml”]<compilerarg value="-Xlint"/>
<!– or –>
<compilerarg value="-Xlint:unchecked"/>[/code]

23)Can you give me a simple ant xslt task example?

Here is a working one!
[code lang=”xml”]<xslt style="${xslfile}" in="${infile}" out="${outfile}" >
<classpath>
<fileset dir="${xml.home}/bin"
includes="*.jar" />
</classpath>
</xslt>
[/code]

24)How to hide password input?

Override ant Input task.
Response every user input with a backspace. Not the best, but it works

25)How do I add elements to an existing path dynamically?

Yes, it is possible. However, you need to write a custom ant task, get the path, and add/modify it, and put it in use. What I am doing is that I define a path reference lib.classpath, then add/modify the lib.classpath use my own task.

26)How to do conditional statement in ant?

There are many ways to solve the problem.

  • Since target if/unless all depend on some property is defined or not, you can use condition to define different NEW properties, which
    in turn depends on your ant property values. This makes your ant script very flexible, but a little hard to read.
  • Ant-contrib has <if> <switch> tasks for you to use.
  • Ant-contrib also has <propertyregex> which can make very complicate decisions.

27)Can I change/override ant properties when I use ant-contrib foreach task?

<foreach> is actually using a different property space, you can pass any property name/value pair to it. Just use <param> nested tag inside foreach

28)How to let auto-detect platform and use platform specific properties?

Tell you a great trick, it works excellent.
In your major build-include.xml, put in this line

[code lang=”xml”] <property file="${antutil.includes}/${os.name}-${os.arch}.properties" />[/code]

This will auto-detect your platform, and you write one file for each environment specific variables. For example: HP-UX-PA_RISC2.0.properties SunOS-sparc.properties Windows XP-x86.properties … They work great!!!

29)How to make ant user interactive? I tried to use BufferedReader to get user input, it hangs.

See here.

Use this class TimedBufferedReader instead of your BufferedReader will work. This is a working one in our installation process. The original author is credited in the code. I’ve made some improvement.

[code lang=”java”]package setup;

import java.io.Reader;
import java.io.BufferedReader;
import java.io.IOException;

/**
* Provides a BufferedReader with a readLine method that
* blocks for only a specified number of seconds. If no
* input is read in that time, a specified default
* string is returned. Otherwise, the input read is returned.
* Thanks to Stefan Reich
* for suggesting this implementation.
* @author: Anthony J. Young-Garner
* @author: Roseanne Zhang made improvement.
*/

public class TimedBufferedReader extends BufferedReader
{
private int timeout = 60; // 1 minute
private String defaultStr = "";

/**
* TimedBufferedReader constructor.
* @param in Reader
*/
TimedBufferedReader(Reader in)
{
super(in);
}

/**
* TimedBufferedReader constructor.
* @param in Reader
* @param sz int Size of the input buffer.
*/
TimedBufferedReader(Reader in, int sz)
{
super(in, sz);
}

/**
* Sets number of seconds to block for input.
* @param seconds int
*/
public void setTimeout(int timeout)
{
this.timeout=timeout;
}

/**
* Sets defaultStr to use if no input is read.
* @param str String
*/
public void setDefaultStr(String str)
{
defaultStr = str;
}

/**
* We use ms internally
* @return String
*/
public String readLine() throws IOException
{
int waitms = timeout*1000;
int ms = 0;
while (!this.ready())
{
try
{
Thread.currentThread().sleep(10);
ms += 10;
}
catch (InterruptedException e)
{
break;
}
if (ms >= waitms)
{
return defaultStr;
}
}
return super.readLine();
}
}[/code]

30)What is a good directory structure for main code and junit test code?

Dev

|_src

| |_com

| |_mycom

| |_mypkg

|
|_A.java

|_test

|_src

|_com

|_mycom

|_mypkg

|_ATest.java

Filed Under: Interview Questions Tagged With: Apache Ant

Quartz Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

What is Quartz?

Quartz is a job scheduling system that can be integrated with, or used along side virtually any other software system. The term “job scheduler” seems to conjure different ideas for different people. As you read this tutorial, you should be able to get a firm idea of what we mean when we use this term, but in short, a job scheduler is a system that is responsible for executing (or notifying) other software components when a pre-determined (scheduled) time arrives.

Quartz is quite flexible, and contains multiple usage paradigms that can be used separately or together, in order to achieve your desired behavior, and enable you to write your code in the manner that seems most ‘natural’ to your project.

Quartz is very light-weight, and requires very little setup/configuration – it can actually be used ‘out-of-the-box’ if your needs are relatively basic.

Quartz is fault-tolerant, and can persist (‘remember’) your scheduled jobs between system restarts.

Although Quartz is extremely useful for simply running certain system processes on given schedules, the full potential of Quartz can be realized when you learn how to use it to drive the flow of your application’s business processes.
What is Quartz – From a Software Component View?

Quartz is distributed as a small java library (.jar file) that contains all of the core Quartz functionality. The main interface (API) to this functionality is the Scheduler interface. It provides simple operations such as scheduling/unscheduling jobs, starting/stopping/pausing the scheduler.

If you wish to schedule your own software components for execution they must implement the simple Job interface, which contains the method execute(). If you wish to have components notified when a scheduled fire-time arrives, then the components should implement either the TriggerListener or JobListener interface.

The main Quartz ‘process’ can be started and ran within your own application, as a stand-alone application (with an RMI interface), or within a J2EE app. server to be used as a resource by your J2EE components.

Why not just use java.util.Timer?

Since JDK 1.3, Java has “built-in” timer capabilities, through the java.util.Timer and java.util.TimerTask classes – why would someone use Quartz rather than these standard features?

There are many reasons! Here are a few:

  1. Timers have no persistence mechanism.
  2. Timers have inflexible scheduling (only able to set start-time & repeat interval, nothing based on dates, time of day, etc.)
  3. Timers don’t utilize a thread-pool (one thread per timer)
  4. Timers have no real management schemes – you’d have to write your own mechanism for being able to remember, organize and retreive your tasks by name, etc.

…of course to some simple applications these features may not be important, in which case it may then be the right decision not to use Quartz.

How can I control the instantiation of Jobs?

See org.quartz.spi.JobFactory and the org.quartz.Scheduler.setJobFactory(..) method.

How do I keep a Job from being removed after it completes?

Set the property JobDetail.setDurability(true) – which instructs Quartz not to delete the Job when it becomes an “orphan” (when the Job not longer has a Trigger referencing it).

How do I keep a Job from firing concurrently?

Make the job class implement StatefulJob rather than Job. Read the JavaDOC for StatefulJob for more information.

How do I stop a Job that is currently executing?

See the org.quartz.InterruptableJob interface, and the Scheduler.interrupt(String, String) method.

How do I chain Job execution? Or, how do I create a workflow?

There currently is no “direct” or “free” way to chain triggers with Quartz. However there are several ways you can accomplish it without much effort. Below is an outline of a couple approaches:

One way is to use a listener (i.e. a TriggerListener, JobListener or SchedulerListener) that can notice the completion of a job/trigger and then immediately schedule a new trigger to fire. This approach can get a bit involved, since you’ll have to inform the listener which job follows which – and you may need to worry about persistence of this information.

Another way is to build a Job that contains within its JobDataMap the name of the next job to fire, and as the job completes (the last step in its execute() method) have the job schedule the next job. Several people are doing this and have had good luck. Most have made a base (abstract) class that is a Job that knows how to get the job name and group out of the JobDataMap using special keys (constants) and contains code to schedule the identified job. Then they simply make extensions of this class that included the additional work the job should do.

In the future, Quartz will provide a much cleaner way to do this, but until then, you’ll have to use one of the above approaches, or think of yet another that works better for you.

Why isn’t my trigger firing?

The most common reason for this is not having called Scheduler.start(), which tells the scheduler to start firing triggers.

The second most common reason is that the trigger or trigger group has been paused.

Daylight Saving Time and Triggers

CronTrigger and SimpleTrigger each handle daylight savings time in their own way – each in the way that is intuitive to the trigger type.

First, as a review of what daylight savings time is, please read this resource: http://webexhibits.org/daylightsaving/g.html . Some readers may be unaware that the rules are different for different nations/contents. For example, the 2005 daylight savings time starts in the United States on April 3, but in Egypt on April 29. It is also important to know that not only the dates are different for different locals, but the time of the shift is different as well. Many places shift at 2:00 am, but others shift time at 1:00 am, others at 3:00 am, and still others right at midnight.

SimpleTrigger allows you to schedule jobs to fire every N milliseconds. As such, it has to do nothing in particular with respect to daylight savings time in order to “stay on schedule” – it simply keeps firing every N milliseconds. Regardless your SimpleTrigger is firing every 10 seconds, or every 15 minutes, or every hour or every 24 hours it will continue to do so. However the implication of this which confuses some users is that if your SimpleTrigger is firing say every 12 hours, before daylight savings switches it may be firing at what appears to be 3:00 am and 3:00 pm, but after daylight savings 4:00 am and 4:00 pm. This is not a bug – the trigger has kept firing exacly every N milliseconds, it just that the “name” of that time that humans impose on that moment has changed.

CronTrigger allows you to schedule jobs to fire at certain moments with respect to a “gregorian calendar”. Hence, if you create a trigger to fire every day at 10:00 am, before and after daylight savings time switches it will continue to do so. However, depending on whether it was the Spring or Autumn daylight savings event, for that particular Sunday, the actual time interval between the firing of the trigger on Sundary morning at 10:00 am since its firing on Saturday morning at 10:00 am will not be 24 hours, but will instead be 23 or 25 hours respectively.

There is one additional point users must understand about CronTrigger with respect to daylight savings. This is that you should take careful thought about creating schedules that fire between midnight and 3:00 am (the critical window of time depends on your trigger’s locale, as explained above). The reason is that depending on your trigger’s schedule, and the particular daylight event, the trigger may be skipped or may appear to not fire for an hour or two. As examples, say you are in the United States, where daylight savings events occur at 2:00 am. If you have a CronTrrigger that fires every day at 2:15 am, then on the day of the beginning of daylight savings time the trigger will be skipped, since, 2:15 am never occurs that day. If you have a CronTrigger that fires every 15 minutes of every hour of every day, then on the day daylight savings time ends you will have an hour of time for which no triggerings occur, because when 2:00 am arrives, it will become 1:00 am again, however all of the firings during the one o’clock hour have already occurred, and the trigger’s next fire time was set to 2:00 am – hence for the next hour no triggerings will occur.

How do I improve the performance of JDBC-JobStore?

There are a few known ways to speed up JDBC-JobStore, only one of which is very practical.

First, the obvious, but not-so-practical:
* Buy a better (faster) network between the machine that runs Quartz, and the machine that runs your RDBMS.

* Buy a better (more powerful) machine to run your database on.

* Buy a better RDBMS.

Now for something simple, but effective: Build indexes on the Quartz tables.

Most database systems will automatically put indexes on the primary-key fields, many will also automatically do it for the foreign-key field. Make sure yours does this, or make the indexes on all key fields of every table manually.

Next, manually add some additional indexes: most important to index are the TRIGGER table’s “next_fire_time” and “state” fields. Last (but not as important), add indexes to every column on the FIRED_TRIGGERS table.

Create Table Indexes

[code]create index idx_qrtz_t_next_fire_time on qrtz_triggers(NEXT_FIRE_TIME);
create index idx_qrtz_t_state on qrtz_triggers(TRIGGER_STATE);
create index idx_qrtz_t_nf_st on qrtz_triggers(TRIGGER_STATE,NEXT_FIRE_TIME);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_group on qrtz_fired_triggers(TRIGGER_GROUP);
create index idx_qrtz_ft_trig_name on qrtz_fired_triggers(TRIGGER_NAME);
create index idx_qrtz_ft_trig_n_g on qrtz_fired_triggers(TRIGGER_NAME,TRIGGER_GROUP);
create index idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers(INSTANCE_NAME);
create index idx_qrtz_ft_job_name on qrtz_fired_triggers(JOB_NAME);
create index idx_qrtz_ft_job_group on qrtz_fired_triggers(JOB_GROUP);[/code]

My DB Connections don’t recover properly if the database server is restarted.

If you’re having Quartz create the connection data source (by specifying the connection parameters in the quartz properties file) make sure you have a connection validation query specified, such as:
Connection Validation Query

org.quartz.dataSource.myDS.validationQuery=select 0 from dual

This particular query is extremly efficient for Oracle. For other databases, you’ll need to think of an efficient query that always works as long as the connection is good.

If you’re datasource is managed by your application server, make sure the datasource is configured in such a way that it can detect failed connections.

I’m using JobStoreCMT and I’m seeing deadlocks, what can I do?

JobStoreCMT is in heavy use, under heavy load by many people. It is believed to be free of bugs that can cause deadlock. However, every now and then we get complaints about deadlocks. In all cases thus far, the problem has turned out to be “user error”, thus the list below is some things for you to check if you are experiencing deadlocks.
[code]
* Some databases falsely detect deadlocks when a tx takes a long time. Make sure you have put indexes on your tables (see improving performance of JDBCJobStore).
* Make sure you have at least number-of-threads-in-thread-pool + 2 connections in your datasources.
* Make sure you have both a managed and non-managed datasource configured for Quartz to use.
* Make sure that all work you do with the Scheduler interface is done from within a transaction. Accomplish this by using the Scheduler within a SessionBean that has its tx settings "Required" and "Container". Or within a MessageDrivenBean with similar settings. Finally, start a UserTransaction yourself, and commit the work when done.
* If your Jobs’ execute() methods use the Scheduler, make sure a transaction is in progress by using a UserTransaction or by setting the Quartz config propery "org.quartz.scheduler.wrapJobExecutionInUserTransaction=true".[/code]

Filed Under: Interview Questions Tagged With: Quartz Scheduler

  • 1
  • 2
  • 3
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved