Monday, January 30, 2006
FAQ on Java Security Part 1
| Is Java secure? Nothing in life is completely secure; Java is no exception. Several specific security problems have been discovered and fixed since Java was first released. If you're using an up-to-date Web browser, you are usually safe against the known attacks. However, nobody is safe against attacks that haven't been discovered yet. If somebody says Java is safe because ``hackers aren't smart enough to exploit the problems,'' don't believe them. We're disappointed that some people who should know better are still spouting this nonsense. We've discovered several security problems, and we're pretty sure we're not the smartest people in the world. If one group of hackers creates a Java-based attack and shares it with their friends, we're all in trouble. Other Web ``scripting'' tools such as JavaScript, Visual Basic Script, or ActiveX face the same sorts of problems as Java. ``Plug-in'' mechanisms provide no security protection. If you install a plug-in, you're trusting that plug-in to be harmless. What are the risks? There are two classes of security problems: nuisances and security breaches. A nuisance attack merely prevents you from getting your work done - for example it may cause your computer to crash. Security breaches are more serious: your files could be deleted, your private data could be read, or a virus could infect your machine. If you are the victim of a security breach, any data stored on your machine may be read or corrupted by a bad guy. If you've got important company secrets on your computer, maybe you should surf the net on another machine. In the not-too-distant future, your computer may be able to digitally sign documents that are legally binding, just like your paper signature. Your computer may also be able to spend your money. In a world like that, security becomes even more important than it is right now. How common are security breaches? So far, there have been no publicly reported, confirmed cases of security breaches involving Java, though there have been some suspicious events that might possibly have involved Java security problems. Of course, the lack of reported cases is no guarantee that there haven't been breaches that either weren't discovered or weren't reported. But it does indicate that breaches are rare. Who is at risk? You're at risk if you're running a Java-enabled browser and you visit a Web page written by a person you don't know or don't trust. Since the two most common browsers, Netscape Navigator and Microsoft Internet Explorer, are Java-enabled, most people surfing the Web are at risk. How can I protect myself? If you maintain sensitive data on your computer that you think an unscrupulous adversary might want, you should disable Java and JavaScript, as well as not installing plug-ins, except from well-known vendors. If you don't disable Java or JavaScript, think twice before visiting a Web site belonging to a person you don't know or don't trust. Of course, some people will be perfectly happy just living with the risk. You can reduce the damage caused by a potential security breach by taking common-sense precautions like backing up your data frequently and keeping sensitive data off your Web-surfing machine. What about products that claim to detect malicious applets? We are skeptical about these products. They probably can't hurt, but don't let yourself get a false sense of security from using them. What about products that claim to block Java applets at a firewall? Recent research by David Martin, S. Rajagopalan, and Avi Rubin suggests that it is extremely difficult, if not impossible, to do this, so we suspect that these products can be bypassed by sophisticated attackers. If you want to block Java, the best way to do it is by setting your browser preferences to disable Java. How can I restrict which sites my browser will accept applets from? We are about to release a prototype tool that lets you do this. Won't digital signatures solve all of the problems? No, they'll only help a little. Digital signatures let you know who wrote an applet, but they don't help you decide whether you can trust the author. Is this problem ever going to go away? No. Security will always be an issue with any network software. As long as vendors are racing their products out the door and adding new functionality with each and every release, you can expect security bugs will always exist. Writing crash-proof software is hard. Writing secure software is even harder. Which is more secure: Netscape Navigator or Microsoft Internet Explorer? In our judgement, the latest versions of the two browsers offer roughly comparable levels of security. Which version of my browser should I use? Generally, the latest version is the safest. Be sure to regularly check your browser vendor's Web pages for announcements of new versions. Look carefully - the announcements are not always prominent. What about ``hostile applets?'' This is a general term for Java applets (programs) that exploit security bugs. There are some pages on the Web that demonstrate, with appropriate warning messages, some hostile applets. The applets we've seen are nuisance attacks rather than damaging attacks. I run a Web server. Am I at risk? Not directly. But watch out for some newer servers that support "servlets". Servlets are fine if they are all written by the people running the server site; using servlets in this way is probably better than using CGI scripts. Going beyond this to let clients upload Java servlets into your server is very risky. Of course, you should be careful about which Java applets appear on your server. Unless you wrote the applet yourself, you don't necessarily know what it's doing. If you copy somebody else's applet, it could possibly be a trojan horse - doing something useful as well as being malicious. What about JavaScript? Java and JavaScript, despite the similarity of their names, are not related. (Isn't marketing wonderful?) JavaScript has its own security problems, so you may also want to disable JavaScript. |
How do I produce well-formed XML with Velocity?
| The title pretty much says it all. I’ve been reading the docs, googling around and asking the only person I know who actually likes Velocity, but I could not find a solution to this simple question: Is it possible to guarantee that the output of a Velocity template will always be a well-formed XML document? Of course, the template must have all tags balanced and such, to start with. Consider this simple template: As long as the string representation of the value variable in the Velocity context is something innocuous as “foobar”, everything is fine. But if it were “foo & bar” instead, you’d get this output: which is most definitely not valid XML! The correct output should have been: So there must be a solution. Of course, there is a really obvious and bad solution, which is going over all the values passed into the Velocity context and escaping all XML special characters like ‘&’, ‘<’ and so on. This might work for a simple case like the one above, but would break down horribly when your data model is a complex collection of arbitrary objects. Please, don’t tell me that Velocity sucks as much as I think it does! |
Wednesday, January 25, 2006
JMS and Websphere Interview Questions
| 1)Can JMS utilities automatically re-establish a connection if one side of the communication link (i.e. an application that's sending/receiving messages) goes down and is restarted? Are there APIs to help detect that the other side broke a connection (went down)? 2)Must i place all my class files in the WEB-INF folder and all JSP's outside? 3)What is the difference between queue and topic? 4)What is the difference between Message producer and Message consumer? 5)What is Producer, Consumer? 6)What is JMS? 7)What is the difference between Point to Point and Publish/Subscribe Messaging Domains? 9)Can JMS utilities automatically re-establish a connection if one side of the communication link (i. e. . . 11)What is true regarding the role Oracle Net provides in a client server connection 12)with no middle. . . 13)What is silly window syndrome 14)What is logical link control 15)Oracle Net is responsible for establishing and maintaining the connection between the client app. . . 16)You are developing a client/server application. The client application will access only some of the . . . 17)You are developing a client/server application. The client application will access only some of . . . 18)What is Message Oriented Middleware (MOM) 19)Explain the building blocks of Client/Server 20)If a performance characteristic is assigned a LSL and USL, it is considered to have a ________ tole. . |
Tuesday, January 24, 2006
Security Tradeoffs: Java vs. ActiveX
| What are Java and ActiveX? Java and ActiveX are two systems that let people attach computer programs to Web pages. People like these systems because they allow Web pages to be much more dynamic and interactive than they could be otherwise. However, Java and ActiveX do introduce some security risk, because they can cause potentially hostile programs to be automatically downloaded and run on your computer, just because you visited some Web page. The downloaded program could try to access or damage the data on your machine, for example to insert a virus. Both Java and ActiveX take measures to protect your from this risk. There has been a lot of public debate over which system offers better security. This page gives our opinion on this debate. Java and ActiveX take fundamentally different approaches to security. We will concentrate on comparing the approaches, rather than critiquing the details of the two systems. After all, details can be fixed. Who are the players? Java was developed by JavaSoft, a division of Sun Microsystems. Java is supported by both of the major browsers, Netscape Navigator and Microsoft Internet Explorer. ActiveX was developed by Microsoft. It is supported in Microsoft's Internet Explorer, and an ActiveX plug-in is available for Netscape Navigator. The most intense public debate about security has been between JavaSoft and Microsoft. Each company has accused the other of being careless about security, and some misleading charges have been made. How does security work in ActiveX? ActiveX security relies entirely on human judgement. ActiveX programs come with digital signatures from the author of the program and anybody else who chooses to endorse the program. Think of a digital signature as being like a person's signature on paper. Your browser can look at a digital signature and see whether it is genuine, so you can know for sure who signed a program. (That's the theory, at least. Things don't always work out so neatly in practice.) Once your browser has verified the signatures, it tells you who signed the program and asks you whether or not to run it. You have two choices: either accept the program and let it do whatever it wants on your machine, or reject it completely. ActiveX security relies on you to make correct decisions about which programs to accept. If you accept a malicious program, you are in big trouble. How does security work in Java? Java security relies entirely on software technology. Java accepts all downloaded programs and runs them within a security "sandbox". Think of the sandbox as a security fence that surrounds the program and keeps it away from your private data. As long as there are no holes in the fence, you are safe. Java security relies on the software implementing the sandbox to work correctly. How can ActiveX security break down? The main danger in ActiveX is that you will make the wrong decision about whether to accept a program. One way this can happen is that some person you trust turns out not to deserve that trust. The most dangerous situation, though, is when the program is signed by someone you don't know anything about. You'd really like to see what this program does, but if you reject it you won't be able to see anything. So you rationalize: the odds that this particular program is hostile are very small, so why not go ahead and accept it? After all, you accepted three programs yesterday and nothing went wrong. It's just human nature to accept the program. Even if the risk of accepting one program is low, the risk adds up when you repeatedly accept programs. And when you do get the one bad program, there is no limit on how much damage it can do. The only way to avoid this scenario is to refuse all programs, no matter how fun or interesting they sound, except programs that come from a few people you know well. Who has the self-discipline to do that? How can Java security break down? The main danger in Java comes from the complexity of the software that implements the sandbox. Common sense says that complicated technology is more likely to break down than simple technology. Java is pretty complicated, and several breakdowns have happened in the past. If you're the average person, you don't have the time or the desire to examine Java and look for implementation errors. So you have to hope the implementers did everything right. They're smart and experienced and motivated, but that doesn't make them infallible. When Java security does break down, the potential consequences are just as bad as those of an ActiveX problem: a hostile program can come to your machine and access your data at will. What about "signed applets" in Java? One problem with the original version of Java is that the "sandbox" can be too restrictive. For example, Java programs are not allowed to access files, so there's no way to write a text editor. (What good is editing if you can't save your work?) Java-enabled products are now starting to use digital signatures to work around this problem. The idea is like ActiveX: programs are digitally signed and you can decide, based on the signature, to give a program more power than it would otherwise have. This lets you run a text editor program if you decide that you trust its author. The downside of this scheme is that it introduces some of the ActiveX problems. If you make the wrong decision about who to trust, you could be very sorry. There's no known way to get around this dilemma. Some kinds of programs must be given power in order to be useful, and there's no ironclad guarantee that those programs will be well-behaved. Still, Java with signed applets does offer some advantages over ActiveX. You can put only partial trust in a program, while ActiveX requires either full trust or no trust at all. And a Java-enabled browser could keep a record of which dangerous operations are carried out by each trusted program, so it would be easier to reconstruct what happened if anything went wrong. (Current browsers don't do this record-keeping, but we wish they would.) Finally, Java offers better protection against accidental damage caused by buggy programs. What about plug-ins? Plug-ins are a method for adding code to your browser. Plug-ins have the same security model as ActiveX: when you download a plug-in, you are trusting it to be harmless. All of the warnings about ActiveX programs apply to plug-ins too. Can I be hurt by a "good" plug-in or ActiveX program? Unfortunately, yes. This depends entirely on what the plug-in or program does. Many plug-ins such as Macromedia's Shockwave or Sun's Safe-Tcl are actually completely general programming systems, just like Java. By accepting a plug-in like this, you're trusting that the plug-in program has no security-relevant bugs. As we have seen with Java, systems that are meant to be secure often have bugs that lead to security problems. With ActiveX, this problem is made worse if you click the box which accepts all programs signed by the same person (for example, if you accept anything signed by Microsoft). While one Microsoft program may be secure, another one may have a security-relevant bug. This problem even applies to code written by your own company for internal use. Once the plug-in or program is installed in your browser, an external attacker (who knew about the program) could write a Web page which used your internal program bug passed it funny data which corrupted the program and took over your machine. If you're feeling paranoid, the only plug-ins you should allow are those with less than general purpose functionality. A plug-in which handles a new image, video, or audio format is less likely to be exploitable than a plug-in for a completely general animation system. This sounds pretty scary. How worried should I be? The good news is that there have been few incidents of people being damaged by hostile Java or ActiveX programs. The reason is simply that the people with the skills to create malicious programs have chosen not to do so. For most people, continuing to use Java and ActiveX is the right choice. If you are informed about the risks, you can make a rational decision to accept some danger in exchange for the benefits of using Java and ActiveX. How can I lower my risk? There are several things you can do. Think very carefully before accepting a digitally signed program. How competent and trustworthy is the signer? Use up-to-date browser versions, and install the security patches offered by your browser vendor. Never surf the Web on a computer that contains highly sensitive information like medical records. |
Thursday, January 19, 2006
Java Interview Questions Part 7
| What are the steps involved in Applet development? Following are the steps involved in Applet development: Create/Edit a Java source file. This file must contain a class which extends Applet class. Compile your program using javac Execute the appletviewer, specifying the name of your applet’s source file or html file. In case the applet information is stored in html file then Applet can be invoked using java enabled web browser. Which method is used to output a string to an applet? Which function is this method included in? drawString( ) method is used to output a string to an applet. This method is included in the paint method of the Applet. Why we can not extends two classes in Java? Trying to extend 2 classes, or multiple inheritence, would result in a few problems. One of it is when you use the super() method. If you use that while extending more then 1 class, which superclass are you referring to then? Java solves this problem by thus using implementations for its multiple inheritence purposes. What gives Java its “write once and run anywhere” nature? Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent. What are the four corner stones of OOP? Abstraction, Encapsulation, Polymorphism and Inheritance. Difference between a Class and an Object? A class is a definition or prototype whereas an object is an instance or living representation of the prototype. What is the difference between method overriding and overloading? Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments. What is a “stateless” protocol? Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination. What is constructor chaining and how is it achieved in Java? A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement. What is passed by ref and what by value? All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references Can RMI and Corba based applications interact? Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP. You can create a String object as String str = “abc"; Why cant a button object be created as Button bt = “abc";? Explain - The main reason you cannot create a button by Button bt1= “abc"; is because “abc” is a literal string (something slightly different than a String object, by the way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = “abc"; What does the “abstract” keyword mean in front of a method? A class? Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract. How many methods do u implement if implement the Serializable Interface? The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are java.rmi.Remote java.util.EventListener What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)? It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use “Timer", I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in. What is the difference between logical data independence and physical data independence? Logical Data Independence - meaning immunity of external schemas to changeds in conceptual schema. Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema. What is a user-defined exception? Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class. Describe the visitor design pattern? Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy. What methods can be overridden in Java? In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private. Can there be an abstract class with no abstract methods in it? Yes Can an Interface be final? No |
Java Interview Questions Part 6
| How do Applets differ from Applications? Following are the main differences: Application: Stand Alone, doesn’t need web-browser. Applet: Needs no explicit installation on local machine. Can be transferred through Internet on to the local machine and may run as part of web-browser. Application: Execution starts with main() method. Doesn’t work if main is not there. Applet: Execution starts with init() method. Application: May or may not be a GUI. Applet: Must run within a GUI (Using AWT). This is essential feature of applets. Can we pass parameters to an applet from HTML page to an applet? How? We can pass parameters to an applet using tag in the following way: Access those parameters inside the applet is done by calling getParameter() method inside the applet. Note that getParameter() method returns String value corresponding to the parameter name. How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string? Use the parseInt() method in the Integer Class, the Float(String) constructor or parseFloat() method in the Class Float, or the Double(String) constructor or parseDoulbl() method in the class Double. How can I arrange for different applets on a web page to communicate with each other? Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method in your applet code to obtain references to the other applets on the page. How do I select a URL from my Applet and send the browser to that page? Ask the applet for its applet context and invoke showDocument() on that context object. URL targetURL; String URLString AppletContext context = getAppletContext(); try { targetURL = new URL(URLString); } catch (MalformedURLException e) { // Code for recover from the exception } context. showDocument (targetURL); Can applets on different pages communicate with each other? - No, Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system. How do I determine the width and height of my application? Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields. The following code snippet explains this: Dimension dim = getSize(); int appletwidth = dim.width(); int appletheight = dim.height(); Which classes and interfaces does Applet class consist? Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub, and AudioClip. What is AppletStub Interface? The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface. What tags are mandatory when creating HTML to display an applet? name, height, width code, name codebase, height, width code, height, width Correct answer is d. What are the Applet’s information methods? The following are the Applet’s information methods: getAppletInfo() method: Returns a string describing the applet, its author, copyright information, etc. getParameterInfo( ) method: Returns an array of string describing the applet’s parameters. |
Monday, January 16, 2006
THE OBSERVER PATTERN
| Like the Singleton Pattern, which was covered in the first half of this tip, the Observer pattern is a popular design pattern used in Java programs. The pattern is a behavioral design pattern. It defines a way for classes to be loosely coupled and for one class (or many) to be notified when another is updated. Basically, this means that when something happens in one place, you notify anyone who is observing and that is interested in that one place. There are two ways to look at the Observer pattern. The first way involves the Observer and Observable classes found in the java.util package. The second way follows the JavaBeans component model of registering event listeners with components. Prior to the creation of the JavaBeans event model, the Observer and Observable classes described an implementation of the Observable pattern. In other words, the classes have been around since the 1.0 version of the Java platform. There is nothing technically wrong with the classes and they are still present in the libraries. The classes still could be used to implement the Observable pattern, but the second model, the JavaBeans component model, is typically used. One significant problem in using the classes to implement the Observable pattern is that you have to extend Observable. This forces a class hierarchy structure that might not be possible in the single-inheritence world of the Java platform. The JavaBeans component model of registering event listeners involves a series of add and remove methods, where the listener type is embedded in the method name. For instance, to observe the selection of a button, you register an ActionListener with the component: ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { ... } }; JButton button = new JButton("Pick Me"); button.addActionListener(listener); That really is all there is to the Observer pattern for the system-defined classes. You implement a listener interface, attach it to the Subject of the observation, and wait. The Subject is what is observed. It is responsible for remembering who is observing. In the JavaBeans component model case, the interface to attach and detach the Observer objects is the add/remove listener naming pattern. When the state of the Subject changes, it notifies the Observer objects. One of the main objectives of the pattern is to enable the loose coupling of the Subject and Observer. When the JButton is selected, instead of calling a specific method of a fictitious subclass named ButtonNotification, the notification is abstracted out into an interface that anyone can implement. The JButton doesn't care what class the attached Observer (listener) is. In fact, the button doesn't care if the implementing class is modified. All it cares about is that the Observer implements a listener. There are a number of complications you need to watch out for when using the Observer pattern. First is the possibility of a memory leak. A reference to the Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector. Be aware of this possibility and remove observers where appropriate. Also note that the set of Observer objects is maintained in an unordered collection -- at least when registering event listeners. You don't necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object A must be notified first, followed by object B, you must introduce an intermediary object to enforce the ordering. Simply registering the observers in a particular order will not enforce their order of notification. Another area of the Java platform that models the Observer pattern is the Java Message Service (JMS), with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified. There are many other places in the Java platform that model the Observer pattern -- the pattern is frequently used throughout the Java platform. Since the 1995 publication of the Design Patterns book by the Gang of Four, other books have been published that offer different perspectives on the same patterns and introduce additional patterns. Two of the more popular titles are: Head First Design Patterns Refactoring to Patterns Other books, such as Patterns of Enterprise Application Architecture are available for those interested in more targeted design pattern coverage -- in this case, for enterprise applications. For more information on design patterns in general, see its Wikipedia entry. This Tech Tips issue is dedicated to the memory of John Vlissides, one of the original Gang of Four authors. He passed away November 2005. |
THE SINGLETON PATTERN
| A design pattern is a general solution to a common problem in software design. The idea is that the solution gets translated into code, and that the code can be applied in different situations where the problem occurs. Discussion of design patterns started with the book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. These four authors are known as the "Gang of Four" or simply "GoF". In their book, the GoF categorized patterns into different subject areas, of which there are three primary areas: creational, structural, and behavioral. Creational patterns describe how objects are created (or "instantiated" in object-oriented terminology). Structural patterns offer help in how to connect and combine objects. Behavioral patterns describe algorithms or communication mechanisms. Some common pattern names are Singleton in the creational area, Observer in the behavioral area, and Facade in the structural area. This Tech Tip describes the Singleton pattern strictly in the context of the Java programming language. One of the commonly used creational patterns is the Singleton pattern. It describes a technique for ensuring that only a single instance of a class is ever created. In essence, the technique takes the following approach: don't let anyone outside the class create instances of the object. Typically, Singletons are lazily created to reduce memory requirements until needed. You can implement this approach in many different ways. If you know the one instance being created will be a subclass, make the parent class abstract and provide a method to get the current instance. An example of this is the Toolkit class in the AWT package. The constructor for Toolkit is public (the default constructor in this particular case): public Toolkit() and the class has a getDefaultToolkit() method for getting the specific subclass -- in this case, the subclass is platform-specific: public static Toolkit getDefaultToolkit() On a Linux platform with the Sun Java runtime, the specific subclass is of type sun.awt.X11.XToolkit. However you don't need to know that because you only access the class through its common abstract parent class, Toolkit. The Collator class is another example of this pattern, with a slight difference. It offers two getInstance() methods. The no-argument version gets the Collator for the default locale. You can pass in your own locale to get the instance of the Collator for that locale. Request the Collator for the same locale multiple times and you get back the same Collator instance. The constructor itself is protected. Similar ways of restricting class creation can be found throughout the J2SE standard libraries. At this point you might think that restricting access to the constructor of a class automatically makes it a Singleton. It doesn't. A case in point is the Calendar class. The Calendar class constructor is protected, and the class offers a getInstance() method to get an instance of the class. However, each call to getInstance() gets a new instance of the class. So that isn't a Singleton. When you create your own Singleton class, make sure that only a single instance is ever created: public class MySingleton { private static final MySingleton INSTANCE = new MySingleton(); private MySingleton() { } public static final MySingleton getInstance() { return INSTANCE; } } The static method, getInstance(), returns the single instance of the class. Note that even if the single instance needs to be a subclass, you don't have to change the API. Theoretically, you don't need the getInstance() method because the INSTANCE variable could be public. However, the getInstance() method does provide flexibility in case of future system changes. Good virtual machine implementations should inline the call to the static getInstance() method. That's not quite all there is to creating a Singleton. If you need to make your Singleton class Serializable, you must provide a readResolve() method: /** * Ensure Singleton class */ private Object readResolve() throws ObjectStreamException { return INSTANCE; } With the readResolve() method in place, deserialization results in the one (and only one) object -- the same object as produced by calls to the getInstance() method. If you don't provide a readResolve() method, an instance of the object is created each time you deserialize the object. The Singleton pattern is useful if you know you only have a single resource, and need to share access to the state information of that single resource. Identifying the need for the Singleton pattern at design time can simplify development. However, sometimes you're not aware of the need until a performance problem leads you to refactor code and use the pattern at a later time. For example, you might discover that system performance is degrading because your program is repeatedly creating instances of the same class to pass along state information. By changing to the Singleton pattern, you avoid recreating the same object. This frees up time the system uses to recreate the object, and saves the time the garbage collector needs to free those instances. In short, use the Singleton design pattern when you want to ensure that one, and only one, instance of a class is ever created. If your constructor doesn't require any operations, provide an empty private constructor (or a protected constructor if you need to subclass). Otherwise, by default, the system will provide a public constructor, something you don't want when working with a Singleton. Note that Singletons are only guaranteed to be unique within a given class loader. If you use the same class across multiple distinct enterprise containers, you'll get one instance for each container. A Singleton pattern is often used with another pattern called the Factory pattern. Like the Singleton pattern, the Factory pattern is a creational pattern. It describes how subclasses of a particular object, or more typically, implementers of a particular interface, do the actual object creation. A good example of the Factory pattern is the Swing BorderFactory class. The class has a series of static methods returning different types of Border objects. It hides the implementation details of the subclasses, allowing the factory to directly call the constructors for the interface implementations. Here's an example of BorderFactory in use: Border line = BorderFactory.createLineBorder(Color.RED); JLabel label = new JLabel("Red Line"); label.setBorder(line); Here, the fact that BorderFactory creates a LineBorder, or how BorderFactory does that, is hidden from the developer. In this particular example, you can directly call the LineBorder constructor, but in many cases of using the Factory pattern, you can't. Frequently, the class implementing the Singleton pattern returns an object to use as a Factory to create instances of a different class. This is exemplified by the PopupFactory class in the way it creates Popup objects. To get the Singleton factory, you call the getSharedInstance() method of PopupFactory: PopupFactory factory = PopupFactory.getSharedInstance(); Then you create a Popup object from the factory by calling the factory's getPopup() method, passing in the parent component, its contents, and position: Popup popup = factory.getPopup(owner, contents, x, y); You'll find the Factory pattern used frequently in a security context. In the following example, a certificate factory is obtained for a particular algorithm, then a certificate for a stream is generated: FileInputStream fis = new FileInputStream(filename); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection c = cf.generateCertificates(fis); As shown with BorderFactory, the Factory pattern does not have to be used with the Singleton pattern. However the two patterns are frequently used together. |
Friday, January 13, 2006
Struts Or JSF? Struts And JSF?
| Struts Struts grew out of a personal need (open source developers often call this scratching your own itch) to support the development of an application that I was responsible for, prior to joining Sun in 2000. My task was to take a US-centric application to Europe, initially in four languages, and make it available (among other delivery channels) on the web. At the time, there was lots of discussion about appropriate architectures for on the JSP-INTEREST mailing list at java.sun.com, but there were few available implementations. Therefore, I set out to create an application framework for my own use, particularly focused on some key functional areas: An architecture based on the Model-View-Controller design patterns commonly seen in rich client applications, focusing on separation of concerns between presentation logic and business logic. A request processing lifecycle that is applied to all incomding HTTP requests, allowing the centralized management of common functionality like input form validation, and invoking business logic via a logical alias, rather than embedding knowledge of the business tier into a view tier component. Robust support for localizing the user interface of a web application. Since I was planning to use JSP for the view tier, a set of JSP custom tags that simplified the creation of user interfaces based on HTML forms. The resulting framework served my needs quite well. As it became obvious that my needs were not unique, I began the process of open sourcing this idea of a web application framework at the Apache Software Foundation. What happened next was nothing short of extraordinary -- Struts quickly became the de facto standard web application architecture in the J2EE space (the number of significant Internet applications built with it is substantial, but is dwarfed by the number of intranet applications that use it), integrated into nearly all the major app servers and tools, supported by a rich ecosystem of knowledgeable proffesionals and skilled developers, backed by significant documentation in the form of books and articles, and the basis for a large user community centered around the Struts User mailing list (to subscribe, send an empty message to user-subscribe@struts.apache.org). As Struts became a common starting point for developers new to the Java platform, an interesting phenomenom was occurring -- for many developers, the key perceived value of using Struts was assumed to be the JSP custom tags for HTML forms. While these tags are quite useful, they do not constitute a robust user interface component model, which has led to the need to create or integrate of third party tag libraries for more complex presentation requirements. To me, the core value has always been in the controller tier (the request processing lifecycle, and the features which this lifecycle has enabled, such as the additions of the Tiles framework for reusable look and feel, and the Validator Framework for client side and server side enforcement of form validation business rules). This perception, then, has led to some of the current confusion. JavaServer Faces After Struts was released, and was beginning to demonstrate its popularity, an increasing number of other frameworks and component implementations were becoming available. Indeed, at one point during the development of JSF, I had pointers to over 50 such technologies on a spreasheet being used to survey the market. While a large amount of innovation occurred, it was difficult to forsee the development of a common standard API for user interface components -- one that would enable the creation of a component marketplace where tools vendors could support one component API instead of 50, and where component developers could count on interoperation with many tools instead of one or two. JSR-127 was introduced with the goal of solving this problem -- providing a common base level API for building user interface components for web applications, with the specific goals of being both accessible to developers writing applications by hand, but also easy to integrate into tools. In order to complete this JSR in any reasonable amount of time (and, if you wish to argue that we didn't achieve this goal, I won't disagree :-), we stayed strictly focused on the view tier. Controller tier functionality was considered out of scope, although to be of any practical use we had to provide hooks for basic things like instantiating objects on demand, as well as support for page navigation. The focus on the view tier was clear from the feature list for JSF 1.0: Standard component API for user interface components, ranging from simple input fields to more complex tree controls and menus, to sophisticated scrollable tables which allowed both input and output. Components also support standard JavaBeans style events and event listeners. Decoupled rendering model, so that the same component could be rendered in different ways (for example, a command component used to submit a form might be rendered as either a button or a hyperlink). Request processing lifecycle focused on the handling of user interface events (such as the node of a tree control being expanded or contracted), coupled with support for data type conversions and component level validation rules. Utility technologies supporting the component APIs, including value binding and method binding expressions, managed beans (create on demand), and page navigation support. JSF 1.0 was released in March 2004, followed by a maintenance release (1.1) in May, and is being rapidly adopted by tools vendors, component writers, and application developers alike. The beginnings of widespread adoption are clearly occurring, and any application which you are about to start should certainly evaluate JSF to see if it meets your needs. Besides the functional APIs described above, you will enjoy the availability of robust tools support from many vendors (shamless plug -- including the product I am currently an architect for, Sun Java Studio Creator). The Bottom Line But what about all those existing Struts applications? Are they going to get left out in the cold, or the developers forced to abandon their existing code and rewrite it? Nothing could be further from the truth. The ideal scenario for existing Struts applications would be that we should be able to migrate, one page at a time (nobody has time to replace their entire UI in one fell swoop) to using JSF component tags -- either the standard ones shipped with JSF, or from any available third party component library -- to improve the richness of the user interface. And, because of the original MVC-based promise of separation of concerns, this migration should require little or no change in the back end functionality of the application (for Struts, that primarily means Action and ActionForm classes). Also, the migration should not eliminate the ability to use key Struts features like Tiles and the Validator Framework. This scenario is, in fact, achieveable. In the Struts source repository is the Struts-Faces Integration Library, that achieves exactly this goal. It is currently available in nightly builds, but will shortly be released as a stand-alone add on library for Struts 1.1 or 1.2 based environments. The nightly builds include two versions of the canonical Struts example application, one using Tiles and one not, both using the Validator Framework. If you have an existing Struts based application, then, I encourage you to evaluate a migration towards using JSF components instead of the original Struts HTML tags. Not only are the original tags effectively superceded by JSF, they are also not undergoing active development at the moment. You will find effectively equivalent functionality in JSF components already available, and much more sophisticated user interface components under development by many providers, for use in the future. For new development, here's the best strategy for determining what to do: Evaluate the two technologies individually, to see if they satisfy your requirements. If one or the other technology is sufficient, go ahead and use it (it's easier to learn and use one technology rather than two where possible); keeping in mind, however, the caveats about Struts HTML tags mentioned above. If your requirements include unique features supported only by Struts (such as Tiles or client side validation support), feel free to use the two frameworks together. The Future It should be clear by now that there is overlap between Struts and JSF, particularly in the view tier. Over time, JSF will continue to evolve in the view tier area, and I'm going to be encouraging the Struts community to focus on value adds in the controller and model tiers. Thus, it will become more and more clear that there is room in many web application architectures for two frameworks, each focused on their own tiers, cooperating to meet overall architectural requirements. The details of this, however, will be the subject of further discussions on the Struts developer mailing list, and (undoubtedly) future blog entries. |
Wednesday, January 11, 2006
Adavance Java Interview Questions Part 3
| What is EJB object ? An object whose class implements the enterprise bean's remote interface. A client never references an enterprise bean instance directly; a client always references an EJB object. The class of an EJB object is generated by a container's deployment tools. What is EJB server ? Software that provides services to an EJB container. For example, an EJB container typically relies on a transaction manager that is part of the EJB server to perform the two-phase commit across all the participating resource managers. The J2EE architecture assumes that an EJB container is hosted by an EJB server from the same vendor, so it does not specify the contract between these two entities. An EJB server can host one or more EJB containers. What is EJB server provider ? A vendor that supplies an EJB server. What is EJB server provider ?What is element ? A unit of XML data, delimited by tags. An XML element can enclose other elements. What is empty tag ? A tag that does not enclose any content What is enterprise bean ? A J2EE component that implements a business task or business entity and is hosted by an EJB container; either an entity bean, a session bean, or a message-driven bean. What is enterprise bean provider ? An application developer who produces enterprise bean classes, remote and home interfaces, and deployment descriptor files, and packages them in an EJB JAR file. What is enterprise information system ? The applications that constitute an enterprise's existing system for handling companywide information. These applications provide an information infrastructure for an enterprise. An enterprise information system offers a well-defined set of services to its clients. These services are exposed to clients as local or remote interfaces or both. Examples of enterprise information systems include enterprise resource planning systems, mainframe transaction processing systems, and legacy database systems. What is enterprise information system resource ? An entity that provides enterprise information system-specific functionality to its clients. Examples are a record or set of records in a database system, a business object in an enterprise resource planning system, and a transaction program in a transaction processing system. What is Enterprise JavaBeans (EJB) ? A component architecture for the development and deployment of object-oriented, distributed, enterprise-level applications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, and secure. What is Enterprise JavaBeans Query Language (EJB QL) ? Defines the queries for the finder and select methods of an entity bean having container-managed persistence. A subset of SQL92, EJB QL has extensions that allow navigation over the relationships defined in an entity bean's abstract schema. What is an entity ? A distinct, individual item that can be included in an XML document by referencing it. Such an entity reference can name an entity as small as a character (for example, <, which references the less-than symbol or left angle bracket, <). An entity reference can also reference an entire document, an external entity, or a collection of DTD definitions. 92. What is entity bean ? An enterprise bean that represents persistent data maintained in a database. An entity bean can manage its own persistence or can delegate this function to its container. An entity bean is identified by a primary key. If the container in which an entity bean is hosted crashes, the entity bean, its primary key, and any remote references survive the crash. What is entity reference ? A reference to an entity that is substituted for the reference when the XML document is parsed. It can reference a predefined entity such as <>94. What is error ? A SAX parsing error is generally a validation error; in other words, it occurs when an XML document is not valid, although it can also occur if the declaration specifies an XML version that the parser cannot handle. See also fatal error, warning. What is Extensible Markup Language ? XML. What is external entity ? An entity that exists as an external XML file, which is included in the XML document using an entity reference. What is external subset ? That part of a DTD that is defined by references to external DTD files. What is fatal error ? A fatal error occurs in the SAX parser when a document is not well formed or otherwise cannot be processed. See also error, warning. What is filter ? An object that can transform the header or content (or both) of a request or response. Filters differ from Web components in that they usually do not themselves create responses but rather modify or adapt the requests for a resource, and modify or adapt responses from a resource. A filter should not have any dependencies on a Web resource for which it is acting as a filter so that it can be composable with more than one type of Web resource. What is filter chain ? A concatenation of XSLT transformations in which the output of one transformation becomes the input of the next. What is finder method ? A method defined in the home interface and invoked by a client to locate an entity bean. |
Adavance Java Interview Questions Part 2
| What is commit ? The point in a transaction when all updates to any resources involved in the transaction are made permanent. What is component contract ? The contract between a J2EE component and its container. The contract includes life-cycle management of the component, a context interface that the instance uses to obtain various information and services from its container, and a list of services that every container must provide for its components. What is component-managed sign-on ? A mechanism whereby security information needed for signing on to a resource is provided by an application component. What is connector ? A standard extension mechanism for containers that provides connectivity to enterprise information systems. A connector is specific to an enterprise information system and consists of a resource adapter and application development tools for enterprise information system connectivity. The resource adapter is plugged in to a container through its support for system-level contracts defined in the Connector architecture. What is Connector architecture ? An architecture for integration of J2EE products with enterprise information systems. There are two parts to this architecture: a resource adapter provided by an enterprise information system vendor and the J2EE product that allows this resource adapter to plug in. This architecture defines a set of contracts that a resource adapter must support to plug in to a J2EE product-for example, transactions, security, and resource management. What is container ? An entity that provides life-cycle management, security, deployment, and runtime services to J2EE components. Each type of container (EJB, Web, JSP, servlet, applet, and application client) also provides component-specific services. What is container-managed persistence ? The mechanism whereby data transfer between an entity bean's variables and a resource manager is managed by the entity bean's container. What is container-managed sign-on ? The mechanism whereby security information needed for signing on to a resource is supplied by the container. What is container-managed transaction ? A transaction whose boundaries are defined by an EJB container. An entity bean must use container-managed transactions. What is content ? In an XML document, the part that occurs after the prolog, including the root element and everything it contains. What is context attribute ? An object bound into the context associated with a servlet. What is context root ? A name that gets mapped to the document root of a Web application. What is conversational state ? The field values of a session bean plus the transitive closure of the objects reachable from the bean's fields. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language, that is, the fields that would be stored by serializing the bean instance. What is CORBA ? Common Object Request Broker Architecture. A language-independent distributed object model specified by the OMG. What is create method ? A method defined in the home interface and invoked by a client to create an enterprise bean. What is credentials ? The information describing the security attributes of a principal. What is CSS ? Cascading style sheet. A stylesheet used with HTML and XML documents to add a style to all elements marked with a particular tag, for the direction of browsers or other presentation mechanisms. What is CTS ? Compatibility test suite. A suite of compatibility tests for verifying that a J2EE product complies with the J2EE platform specification. What is data ? The contents of an element in an XML stream, generally used when the element does not contain any subelements. When it does, the term content is generally used. When the only text in an XML structure is contained in simple elements and when elements that have subelements have little or no data mixed in, then that structure is often thought of as XML data, as opposed to an XML document. What is DDP ? Document-driven programming. The use of XML to define applications. What is declaration ? The very first thing in an XML document, which declares it as XML. The minimal declaration is . The declaration is part of the document prolog. What is declarative security ? Mechanisms used in an application that are expressed in a declarative syntax in a deployment descriptor. What is delegation ? An act whereby one principal authorizes another principal to use its identity or privileges with some restrictions. What is deployer ? A person who installs J2EE modules and applications into an operational environment. What is deployment ? The process whereby software is installed into an operational environment. What is deployment descriptor ? An XML file provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve. What is destination ? A JMS administered object that encapsulates the identity of a JMS queue or topic. See point-to-point messaging system, publish/subscribe messaging system. What is digest authentication ? An authentication mechanism in which a Web application authenticates itself to a Web server by sending the server a message digest along with its HTTP request message. The digest is computed by employing a one-way hash algorithm to a concatenation of the HTTP request message and the client's password. The digest is typically much smaller than the HTTP request and doesn't contain the password. What is distributed application ? An application made up of distinct components running in separate runtime environments, usually on different platforms connected via a network. Typical distributed applications are two-tier (client-server), three-tier (client-middleware-server), and multitier (client-multiple middleware-multiple servers). What is document ? In general, an XML structure in which one or more elements contains text intermixed with subelements. What is Document Object Model ? An API for accessing and manipulating XML documents as tree structures. DOM provides platform-neutral, language-neutral interfaces that enables programs and scripts to dynamically access and modify content and structure in XML documents. What is document root ? The top-level directory of a WAR. The document root is where JSP pages, client-side classes and archives, and static Web resources are stored. What is DTD ? Document type definition. An optional part of the XML document prolog, as specified by the XML standard. The DTD specifies constraints on the valid tags and tag sequences that can be in the document. The DTD has a number of shortcomings, however, and this has led to various schema proposals. For example, the DTD entry says that the XML element called username contains parsed character data-that is, text alone, with no other structural elements under it. The DTD includes both the local subset, defined in the current file, and the external subset, which consists of the definitions contained in external DTD files that are referenced in the local subset using a parameter entity. What is durable subscription ? In a JMS publish/subscribe messaging system, a subscription that continues to exist whether or not there is a current active subscriber object. If there is no active subscriber, the JMS provider retains the subscription's messages until they are received by the subscription or until they expire. What is EAR file ? Enterprise Archive file. A JAR archive that contains a J2EE application. What is ebXML ? Electronic Business XML. A group of specifications designed to enable enterprises to conduct business through the exchange of XML-based messages. It is sponsored by OASIS and the United Nations Centre for the Facilitation of Procedures and Practices in Administration, Commerce and Transport (U.N./CEFACT). What is EJB ? Enterprise JavaBeans. What is EJB container ? A container that implements the EJB component contract of the J2EE architecture. This contract specifies a runtime environment for enterprise beans that includes security, concurrency, life-cycle management, transactions, deployment, naming, and other services. An EJB container is provided by an EJB or J2EE server. What is EJB container provider ? A vendor that supplies an EJB container. What is EJB context ? A vendor that supplies an EJB container. An object that allows an enterprise bean to invoke services provided by the container and to obtain the information about the caller of a client-invoked method. What is EJB home object ? An object that provides the life-cycle operations (create, remove, find) for an enterprise bean. The class for the EJB home object is generated by the container's deployment tools. The EJB home object implements the enterprise bean's home interface. The client references an EJB home object to perform life-cycle operations on an EJB object. The client uses JNDI to locate an EJB home object What is EJB JAR file ? A JAR archive that contains an EJB module. What is EJB module ? A deployable unit that consists of one or more enterprise beans and an EJB deployment descriptor. |
Adavance Java Interview Questions Part 1
| What is J2EE? J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. What is the J2EE module? A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type. What are the components of J2EE application? A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: Application clients and applets are client components. Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components. Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components. Resource adapter components provided by EIS and tool vendors. What are the four types of J2EE modules? 1. Application client module 2. Web module 3. Enterprise JavaBeans module 4. Resource adapter module What does application client module contain? The application client module contains: --class files, --an application client deployment descriptoor. Application client modules are packaged as JAR files with a .jar extension. What does web module contain? The web module contains: --JSP files, --class files for servlets, --GIF and HTML files, and --a Web deployment descriptor. Web modules are packaged as JAR files with a .war (Web ARchive) extension. What are the differences between Ear, Jar and War files? Under what circumstances should we use each one? There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes. --Jar files (files with a .jar extension) arre intended to hold generic libraries of Java classes, resources, auxiliary files, etc. --War files (files with a .war extension) arre intended to contain complete Web applications. In this context, a Web application is defined as a single group of files, classes, resources, .jar files that can be packaged and accessed as one servlet context. --Ear files (files with a .ear extension) arre intended to contain complete enterprise applications. In this context, an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Web applications. Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc. What is the difference between Session bean and Entity bean?one? The Session bean and Entity bean are two main parts of EJB container. Session Bean --represents a workflow on behalf of a cliennt --one-to-one logical mapping to a client. --created and destroyed by a client --not permanent objects --lives its EJB container(generally) does noot survive system shut down --two types: stateless and stateful beans Entity Bean --represents persistent data and behavior off this data --can be shared among multiple clients --persists across multiple invocations --findable permanent objects --outlives its EJB container, survives systeem shutdown --two types: container managed persistence(CCMP) and bean managed persistence(BMP) What is "applet" ? A J2EE component that typically executes in a Web browser but can execute in a variety of other applications or devices that support the applet programming model. What is "applet container" ? A container that includes support for the applet programming model. What is "application assembler" ? A person who combines J2EE components and modules into deployable application units. What is "application client" ? A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs. What is "application client container" ? A container that supports application client components. What is "application client module" ? A software unit that consists of one or more classes and an application client deployment descriptor. What is "application component provider" ? A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors. What is "application configuration resource file" ? An XML file used to configure resources for a JavaServer Faces application, to define navigation rules for the application, and to register converters, validators, listeners, renderers, and components with the application. What is "archiving" ? The process of saving the state of an object and restoring it. What is "asant" ? A Java-based build tool that can be extended using Java classes. The configuration files are XML-based, calling out a target tree where various tasks get executed. What is "attribute"What is "asant" ? A qualifier on an XML tag that provides additional information. What is authentication ? The process that verifies the identity of a user, device, or other entity in a computer system, usually as a prerequisite to allowing access to resources in a system. The Java servlet specification requires three types of authentication-basic, form-based, and mutual-and supports digest authentication. What is authorization? The process by which access to a method or resource is determined. Authorization depends on the determination of whether the principal associated with a request through authentication is in a given security role. A security role is a logical grouping of users defined by the person who assembles the application. A deployer maps security roles to security identities. Security identities may be principals or groups in the operational environment. What is authorization constraint ? An authorization rule that determines who is permitted to access a Web resource collection. What is B2B ? B2B stands for Business-to-business. What is backing bean ? A JavaBeans component that corresponds to a JSP page that includes JavaServer Faces components. The backing bean defines properties for the components on the page and methods that perform processing for the component. This processing includes event handling, validation, and processing associated with navigation. What is basic authentication ? An authentication mechanism in which a Web server authenticates an entity via a user name and password obtained using the Web application's built-in authentication mechanism. What is bean-managed persistence ? The mechanism whereby data transfer between an entity bean's variables and a resource manager is managed by the entity bean. What is bean-managed transaction ? A transaction whose boundaries are defined by an enterprise bean. What is binding (XML) ? Generating the code needed to process a well-defined portion of XML data. What is binding (JavaServer Faces technology) ? Wiring UI components to back-end data sources such as backing bean properties. What is build file ? The XML file that contains one or more asant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project's default target is executed. What is business logic ? The code that implements the functionality of an application. In the Enterprise JavaBeans architecture, this logic is implemented by the methods of an enterprise bean. What is business method ? A method of an enterprise bean that implements the business logic or rules of an application. What is callback methods ? Component methods called by the container to notify the component of important events in its life cycle. What is caller ? Same as caller principal. What is caller principal ? The principal that identifies the invoker of the enterprise bean method. What is cascade delete ? A deletion that triggers another deletion. A cascade delete can be specified for an entity bean that has container-managed persistence. What is CDATA ? A predefined XML tag for character data that means "don't interpret these characters," as opposed to parsed character data (PCDATA), in which the normal rules of XML syntax apply. CDATA sections are typically used to show examples of XML syntax. What is certificate authority ? A trusted organization that issues public key certificates and provides identification to the bearer. What is client-certificate authentication ? An authentication mechanism that uses HTTP over SSL, in which the server and, optionally, the client authenticate each other with a public key certificate that conforms to a standard that is defined by X.509 Public Key Infrastructure. What is comment ? In an XML document, text that is ignored unless the parser is specifically told to recognize it. |
Friday, January 06, 2006
Spring is HOT - An Introduction
| This time I come up with an interesting framework and it's popularity is increasing in the Java development community. The so called framework is Spring. I insisted to learn spring becuase many of the requirements i have seen in the companies mention Spring framework. So, i decided to learn Spring. I have decided to write series of blogs on spring. In this "Spring is HOT - An Introduction" , i will give an introduction to the spring frmework. Future blogs i will explain how to use Spring in the web developement. In this blog i am not going to teach you how to program in spring rather i will explain you what is spring and how it is richer than EJB. If you think Spring is an framework in the place of Struts, you have wrong conception about the Spring . Spring is not only a framework, also it is an container to develope high end enterprise applications. Unlike EJB, it doesn't come up with more complex architecture rather it is a simple framewok to use in our application with all other services(Transaction,Security,etc.) wrapped up your code. All the services are bundled in the different jar files and you just add the required files into your project. Spring uses Plain Old Java Object(POJO) paradigm to implement the services needed for your application. This facilitate the use of Spring framework out of the container. Easy to Unit Test the Spring enabled applications. Another salient feature of Spring is, it allows us to easily integrate with other frameworks like Struts, WebWorks, Hibernate, etc. Spring is built using two programming techniques : Inversion of Control(IoC) and Aspect Oriented Programming(AOP). In my next blog i will write about IoC in detail. Spring is extensively implemented in the Banking solutions. I can see the prosperous year ahead for Spring in 2006. |
List of Web frameworks in Java
| We have lot of opensource frameworks available for Java developement. If we are closely looking at the each one, they have specific feature to highlight from the other frameworks. In this blog i just write the list of frameworks available and give the brief on it. I am not going to write about all the frameworks in the market. I will look into few, which is more familiar with us. Also i may miss some frameworks. I will write those frameworks in my future blogs. Struts Struts is the best implementation for Model View Controller(MVC) pattern and widely accepted by the developers. This framework is originated by the Apache Foundation, a famous open source commuinty in Java. Recent days the Struts framework lossing its popularity to other frameworks in the market Java Server Faces(JSF),Spring,etc. But still its mostly used in all the web applications. Currently this project developement is stopped and started a sub project called Shale. Which is more like Java Server Faces(JSF). Spring Spring is a lightweight container and framework to develope and deploy the enterprise application. It is an alternative for Enterprise Java Beans(EJB). It reduce the complexity behind developing EJB's, and it uses only Plain Old Java Objects(POJOs) as the componenets. It uses two types of programming techniques : Inversion of control (also called as Dependency Injection) and Aspect Oriented Programming(AOP). This framework become more popular amoung the J2EE developers becuse of its simplicity and its more flexible to add the persistance layer which ever you want for your application(ie,Hibernate, DAO,etc). Unlike EJBs it need not force you to add all the service to the container, you have the control of adding services to your application. The main pitfall of EJB is for an simple EJB also you have to bare the cost of container servies. But in spring this overhead is reduced. Every service has been modulrized and you have the option to add into your application. For your convenience, spring framework gives all the services in the different jar files. You can download it from here. Also Spring gives you the MVC pattern to build your web application. This feature makes spring stand out from the other frameworks. Spring contains both container and framework. It gives the better way to integrate with EJBs and Struts framework. Those who feel EJB is more complicated, Spring will be the answer. This framework is developer by Interface21 and home page is SpringFramework. Java Server Faces(JSF) is a java based web framework to develope web applications. Its is used inside an Java Server Pages(JSP) and gives more flexibility to design User Interfaces. This framework is designed and maintained by Sun Micro Systems. Craig McClanahan is the co-specification lead for this framework. Also he is the creator of Struts framework. You can read his blog to find more information about him. From his blog: "It should come as no surprise that the most frequent questions I get asked center around the issue of which of these two web tier technologies an organization or individual developer should consider using. It makes sense to ask me, because I was the original creator of the Struts Framework, and was the co-specification lead for JavaServer Faces 1.0 (JSF).
WebWork's homepage is http://www.opensymphony.com/webwork. |
Wednesday, January 04, 2006
Adavance Java Interview Questions On Servlets Part 2
| What is a servlet? Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface. Whats the advantages using servlets over using CGI? Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension. What are the general advantages and selling points of Servlets? A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries. Which package provides interfaces and classes for writing servlets? javax What’s the Servlet Interface? The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet. When a servlet accepts a call from a client, it receives two objects. What are they? ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package. What information does ServletRequest allow access to? Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods. What type of constraints can ServletResponse interface set on the client? It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data. Explain servlet lifecycle? Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down. How does HTTP Servlet handle client requests? An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request. |
Adavance Java Interview Questions On Servlets Part1
| What is servlet? Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database. What are the classes and interfaces for servlets? There are two packages in servlets and they are javax.servlet and javax.servlet.http. Javax.servlet contains: Interfaces Classes Servlet Generic Servlet ServletRequest ServletInputStream ServletResponse ServletOutputStream ServletConfig ServletException ServletContext UnavailableException SingleThreadModel Javax.servlet.http contains: Interfaces Classes HttpServletRequest Cookie HttpServletResponse HttpServlet HttpSession HttpSessionBindingEvent HttpSessionContext HttpUtils HttpSeesionBindingListener What is the difference between an applet and a servlet? a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces. what is the lifecycle of a servlet. Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client's requests through service( ) method. c) The server removes the servlet through destroy() method. What is the ServletConfig() and why are using ServletConfig ? This interface is implemented by services in order to pass configuration information to a servlet when it is first loaded.A service writer implementing this interface must write methods for the servlet to use to get its initialization parameters and the context in which it is running. public interface ServletConfig What is meant by the ServletContext() and use of the method ? Ans: public interface ServletContext The ServletContext interface gives servlets access to information about their environment ,and allows them to log significant events. Servlet writers decide what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet contexts. What is use of parseQueryString ? Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its keys separated from its values by equal signs (=).) Note: public static Hashtable parseQueryString(String s) what are the types of servlets? Genereic Servlets,HttpServlets. what are the different methods in HttpServlet? doGet(),doPost(),doHead,doDelete(),deTrace() What is the difference between GET and POST? a) doGet() method is used to get information, while doPost( ) method is used for posting information. b) doGet() requests can't send large amount of information and is limited to 240-255 characters. However, doPost( )requests passes all of its data, of unlimited length. c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client. |