Featured FREE Whitepapers

What's New Here?


Design Your Agile Project, Part 2

The point of using agile is to get finish something valuable-to-the-business quickly, to get feedback. Why? For several reasons, but the first one is so you can change the project’s priorities. The second is so you can change the project portfolio. The third is to get feedback on what you’ve done. Okay, you can exchange one, two, and three if you like. For me, those are the top three reasons to get to done every few days to two weeks. They are right behind each other in priority. Agile is all about change. This is why every project needs to design its own way to get to done. If you have a single collocated team, who understands how to deliver value quickly you might be in the situation described in Design Your Agile Project, Part 1. What happens when you have more unknowns? What if your organization is “addicted” to waterfall and long projects? When you can’t see the people on your project, because everyone isn’t in the same place? When you have a lot of technical risk, such as technical debt? How about when you’re starting a program and everyone is transitioning to agile (oh please, don’t do this). Or, you’re new to agile, and you don’t have training. I have a question: would you drive a car on the road with no training, either? Rethinking What to do When Your Project or Organization is Full of UnknownsLet’s discuss the principles of designing your agile project when you have more unknowns. Let’s start with a common problem: an organization “addicted” to waterfall and long projects. And, they’ve heard about this “agile” stuff, and they want to try it. If you have heard about the many places Scrum has failed, this is classic. Scrum says, “replace your old culture with this new culture.” Wow, that’s a big shift. If you look at the Cynefin framework, you can see that for an organization addicted to waterfall, long projects and big requirements, they are not in Complicated. They are in Complex. Why? Because they have too many unknowns. Here’s what I see when I do assessments in these organizations:Much multitasking to address emergencies. No project portfolio management Their requirements are so large, it takes them forevvveerrr to release anything Because their requirements are so large, and because their releases are so long, that increases the demand for emergencies: patches, interim releases, firefighting.There could be more. This is enough. In that case, you want to look at the Cynefin framework, and say, “What does the Complex side of the framework say?” It says we should consider emergent practice. We should not only consider out-of-the-box solutions. We have to probe-sense-respond. What do we need to accomplish? Getting to working software, at the end of an iteration. Or, in flow. We want a feature, in flow, in a day or two, maybe three. We want completed features, with no leftover wasted work (unfinished features) at the end of an iteration. We want to be able to change what we do after the iteration, or after the feature. How do we accomplish that, from the team’s perspective? Let’s forget labels, and focus on the team. What’s the First Thing the Team Could Do? I like to ask, “How little can we do?” Too often, the team has been asking “How much can we do?” Starting with that question helps. Thinking in inch-pebbles, timeb0xing work, spiking work, all of that helps to learn how to work small. Sometimes, when we have stories, and we don’t know how to break them apart, we ask, “What’s the first thing that could add value?” Maybe that’s a good question here. You could ask, “What’s the first thing the team can do?” Or, “What’s the first thing we can do that would help us get to done in a one- or two-week iteration?” Or, “How do we finish a feature in flow (kanban)?” Often, for teams who are in the Complex side of the framework, I suggest these things:Start a kanban board. You need to see what your actual process is. You need the visuals. Decide on your work in progress limits, and stick to them, at least for a week. Retrospect and reflect on those limits, the progress you’ve made and anything else that arose. Where are you, as a team? What progress did you make? What do you want to keep, add, change?Notice how this is not out-of-the-box agile or lean. It’s a way to start a team moving from the Complex to the Complicated. Once a team has been through the first week, they iterate, keeping in mind these principles: Let’s Review the Principles:Get to done, either in flow or iterations. Why? Because we want to develop working software. Keep the iterations short, either one or two weeks. Longer is not better. Why? It’s too long to allow for frequent change. Why? Because we need to allow for change in the project. That way, we can get feedback on the features, change the project’s priorities, and manage the project portfolio. Find a way to connect as a team, regardless of how you do so. Real-time rituals are not good if they make everybody crazy from lack of sleep. Why? We need sustainable development, even if real-time rituals are the best. Find a way to reflect as a team. Surrogate reflection is not good. Why? How can someone else substitute for what’s really going on in a team?Where are we now? Nobody has changed roles. Nobody has changed culture. We are looking at our process, and making things smaller for a while. We are reflecting. All of this in order to simplify, to move from the Complex to the Complicated. Remember, I have only discussed what I have done with teams who are collocated, who have had problems with too-large features, long waterfall projects, and many emergencies. I haven’t addressed the issues of distributed teams yet. They are next. I hope you stay with me as we move to part 3.Reference: Design Your Agile Project, Part 2 from our JCG partner Johanna Rothman at the Managing Product Development blog....

115 Java Interview Questions and Answers – The ULTIMATE List

In this tutorial we will discuss about different types of questions that can be used in a Java interview, in order for the employer to test your skills in Java and object-oriented programming in general. In the following sections we will discuss about object-oriented programming and its characteristics, general questions regarding Java and its functionality, collections in Java, garbage collectors, exception handling, Java applets, Swing, JDBC, Remote Method Invocation (RMI), Servlets and JSP. Let’s go…! Table of ContentsObject Oriented Programming (OOP) General Questions about Java Java Threads Java Collections Garbage Collectors Exception Handling Java Applets Swing JDBC Remote Method Invocation (RMI) Servlets JSPObject Oriented Programming (OOP) Java is a computer programming language that is concurrent, class-based and object-oriented. The advantages of object oriented software development are shown below:Modular development of code, which leads to easy maintenance and modification. Reusability of code. Improved reliability and flexibility of code. Increased understanding of code.Object-oriented programming contains many significant features, such as encapsulation, inheritance, polymorphism and abstraction. We analyze each feature separately in the following sections. Encapsulation Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data. In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below:The internal state of every objected is protected by hiding its attributes. It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended. It improves modularity by preventing objects to interact with each other, in an undesired way.You can refer to our tutorial here for more details and examples on encapsulation. Polymorphism Polymorphism is the ability of programming languages to present the same interface for differing underlying data types. A polymorphic type is a type whose operations can also be applied to values of some other type. Inheritance Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it. Abstraction Abstraction is the process of separating ideas from specific instances and thus, develop classes in terms of their own functionality, instead of their implementation details. Java supports the creation and existence of abstract classes that expose interfaces, without including the actual implementation of all methods. The abstraction technique aims to separate the implementation details of a class from its behavior. Differences between Abstraction and Encapsulation Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of an object. On the other hand, encapsulation focuses on the implementation of an object’s behavior. Encapsulation is usually achieved by hiding information about the internal state of an object and thus, can be seen as a strategy used in order to provide abstraction. General Questions about Java 1. What is JVM ? Why is Java called the “Platform Independent Programming Language” ? A Java virtual machine (JVM) is a process virtual machine that can execute Java bytecode. Each Java source file is compiled into a bytecode file, which is executed by the JVM. Java was designed to allow application programs to be built that could be run on any platform, without having to be rewritten or recompiled by the programmer for each separate platform. A Java virtual machine makes this possible, because it is aware of the specific instruction lengths and other particularities of the underlying hardware platform. 2. What is the Difference between JDK and JRE ? The Java Runtime Environment (JRE) is basically the Java Virtual Machine (JVM) where your Java programs are being executed. It also includes browser plugins for applet execution. The Java Development Kit (JDK) is the full featured Software Development Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile and execute Java applications. 3. What does the “static” keyword mean ? Can you override private or static method in Java ? The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs. A user cannot override static methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class so the concept is not applicable. 4. Can you access non static variable in static context ? A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance. 5. What are the Data Types supported by Java ? What is Autoboxing and Unboxing ? The eight primitive data types supported by the Java programming language are:byte short int long float double boolean charAutoboxing is the automatic conversion made by the Java compiler between the primitive types and their corresponding object wrapper classes. For example, the compiler converts an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this operation is called unboxing. 6. What is Function Overriding and Overloading in Java ? Method overloading in Java occurs when two or more methods in the same class have the exact same name, but different parameters. On the other hand, method overriding is defined as the case when a child class redefines the same method as a parent class. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. 7. What is a Constructor, Constructor Overloading in Java and Copy-Constructor ? A constructor gets invoked when a new object is created. Every class has a constructor. In case the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a default constructor for that class. The constructor overloading is similar to method overloading in Java. Different constructors can be created for a single class. Each constructor must have its own unique parameter list. Finally, Java does support copy constructors like C++, but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own. 8. Does Java support multiple inheritance ? No, Java does not support multiple inheritance. Each class is able to extend only on one class, but is able to implement more than one interfaces. 9. What is the difference between an Interface and an Abstract class ? Java provides and supports the creation both of abstract classes and interfaces. Both implementations share some common characteristics, but they differ in the following features:All methods in an interface are implicitly abstract. On the other hand, an abstract class may contain both abstract and non-abstract methods. A class may implement a number of Interfaces, but can extend only one abstract class. In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract. Abstract classes can implement interfaces without even providing the implementation of interface methods. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public. An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.Also check out the Abstract class and Interface differences for JDK 8. 10. What are pass by reference and pass by value ? When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places. Java Threads 11. What is the difference between processes and threads ? A process is an execution of a program, while a Thread is a single execution sequence within a process. A process can contain multiple threads. A Thread is sometimes called a lightweight process. 12. Explain different ways of creating a thread. Which one would you prefer and why ? There are three ways that can be used in order for a Thread to be created:A class may extend the Thread class. A class may implement the Runnable interface. An application can use the Executor framework, in order to create a thread pool.The Runnable interface is preferred, as it does not require an object to inherit the Thread class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily. 13. Explain the available thread states in a high-level. During its execution, a thread can reside in one of the following states:Runnable: A thread becomes ready to run, but does not necessarily start running immediately. Running: The processor is actively executing the thread code. Waiting: A thread is in a blocked state waiting for some external processing to finish. Sleeping: The thread is forced to sleep. Blocked on I/O: Waiting for an I/O operation to complete. Blocked on Synchronization: Waiting to acquire a lock. Dead: The thread has finished its execution.14. What is the difference between a synchronized method and a synchronized block ? In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock). 15. How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply ? The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock. 16. What’s a deadlock ? A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly. 17. How do you ensure that N threads can access N resources without deadlock ? A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise. Java Collections 18. What are the basic interfaces of Java Collections Framework ? Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are:Collection, which represents a group of objects known as its elements. Set, which is a collection that cannot contain duplicate elements. List, which is an ordered collection and can contain duplicate elements. Map, which is an object that maps keys to values and cannot contain duplicate keys.19. Why Collection doesn’t extend Cloneable and Serializable interfaces ? The Collection interface specifies groups of objects known as elements. Each concrete implementation of a Collection can choose its own way of how to maintain and order its elements. Some collections allow duplicate keys, while some other collections don’t. The semantics and the implications of either cloning or serialization come into play when dealing with actual implementations. Thus, the concrete implementations of collections should decide how they can be cloned or serialized. 20. What is an Iterator ? The Iterator interface provides a number of methods that are able to iterate over any Collection. Each Java Collection contains the iterator method that returns an Iterator instance. Iterators are capable of removing elements from the underlying collection during the iteration. 21. What differences exist between Iterator and ListIterator ? The differences of these elements are listed below:An Iterator can be used to traverse the Set and List collections, while the ListIterator can be used to iterate only over Lists. The Iterator can traverse a collection only in forward direction, while the ListIterator can traverse a List in both directions. The ListIterator implements the Iterator interface and contains extra functionality, such as adding an element, replacing an element, getting the index position for previous and next elements, etc.22. What is difference between fail-fast and fail-safe ? The Iterator's fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a ConcurrentModificationException, while fail-safe iterator never throws such an exception. 23. How HashMap works in Java ? A HashMap in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode and equals methods, in order to put and retrieve elements to and from the collection respectively. When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists, its value is updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing. 24. What is the importance of hashCode() and equals() methods ? A HashMap in Java uses the hashCode and equals methods to determine the index of the key-value pair. These methods are also used when we request the value of a specific key. If these methods are not implemented correctly, two different keys might produce the same hash value and thus, will be considered as equal by the collection. Furthermore, these methods are also used to detect duplicates. Thus, the implementation of both methods is crucial to the accuracy and correctness of the HashMap. 25. What differences exist between HashMap and Hashtable ? Both the HashMap and Hashtable classes implement the Map interface and thus, have very similar characteristics. However, they differ in the following features:A HashMap allows the existence of null keys and values, while a Hashtable doesn’t allow neither null keys, nor null values. A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in single-threaded environments, while a Hashtable is suitable for multi-threaded environments. A HashMap provides its set of keys and a Java application can iterate over them. Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an Enumeration of its keys. The Hashtable class is considered to be a legacy class.26. What is difference between Array and ArrayList ? When will you use Array over ArrayList ? The Array and ArrayList classes differ on the following features:Arrays can contain primitive or objects, while an ArrayList can contain only objects. Arrays have fixed size, while an ArrayList is dynamic. An ArrayListprovides more methods and features, such as addAll, removeAll, iterator, etc. For a list of primitive data types, the collections use autoboxing to reduce the coding effort. However, this approach makes them slower when working on fixed size primitive data types.27. What is difference between ArrayList and LinkedList ? Both the ArrayList and LinkedList classes implement the List interface, but they differ on the following features:An ArrayList is an index based data structure backed by an Array. It provides random access to its elements with a performance equal to O(1). On the other hand, a LinkedList stores its data as list of elements and every element is linked to its previous and next element. In this case, the search operation for an element has execution time equal to O(n). The Insertion, addition and removal operations of an element are faster in a LinkedList compared to an ArrayList, because there is no need of resizing an array or updating the index when an element is added in some arbitrary position inside the collection. A LinkedList consumes more memory than an ArrayList, because every node in a LinkedList stores two references, one for its previous element and one for its next element.Check also our article ArrayList vs. LinkedList. 28. What is Comparable and Comparator interface ? List their differences. Java provides the Comparable interface, which contains only one method, called compareTo. This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object. Java provides the Comparator interface, which contains two methods, called compare and equals. The first method compares its two input arguments and imposes an order between them. It returns a negative integer, zero, or a positive integer to indicate that the first argument is less than, equal to, or greater than the second. The second method requires an object as a parameter and aims to decide whether the input object is equal to the comparator. The method returns true, only if the specified object is also a comparator and it imposes the same ordering as the comparator. 29. What is Java Priority Queue ? The PriorityQueue is an unbounded queue, based on a priority heap and its elements are ordered in their natural order. At the time of its creation, we can provide a Comparator that is responsible for ordering the elements of the PriorityQueue. A PriorityQueue doesn’t allow null values, those objects that doesn’t provide natural ordering, or those objects that don’t have any comparator associated with them. Finally, the Java PriorityQueue is not thread-safe and it requires O(log(n)) time for its enqueing and dequeing operations. 30. What do you know about the big-O notation and can you give some examples with respect to different data structures ? The Big-O notation simply describes how well an algorithm scales or performs in the worst case scenario as the number of elements in a data structure increases. The Big-O notation can also be used to describe other behavior such as memory consumption. Since the collection classes are actually data structures, we usually use the Big-O notation to chose the best implementation to use, based on time, memory and performance. Big-O notation can give a good indication about performance for large amounts of data. 31. What is the tradeoff between using an unordered array versus an ordered array ? The major advantage of an ordered array is that the search times have time complexity of O(log n), compared to that of an unordered array, which is O (n). The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n), because the elements with higher values must be moved to make room for the new element. Instead, the insertion operation for an unordered array takes constant time of O(1). 32. What are some of the best practices relating to the Java Collection framework ?Choosing the right type of the collection to use, based on the application’s needs, is very crucial for its performance. For example if the size of the elements is fixed and know a priori, we shall use an Array, instead of an ArrayList. Some collection classes allow us to specify their initial capacity. Thus, if we have an estimation on the number of elements that will be stored, we can use it to avoid rehashing or resizing. Always use Generics for type-safety, readability, and robustness. Also, by using Generics you avoid the ClassCastException during runtime. Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map, in order to avoid the implementation of the hashCode and equals methods for our custom class. Program in terms of interface not implementation. Return zero-length collections or arrays as opposed to returning a null in case the underlying collection is actually empty.33. What’s the difference between Enumeration and Iterator interfaces ? Enumeration is twice as fast as compared to an Iterator and uses very less memory. However, the Iterator is much safer compared to Enumeration, because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, Iteratorsallow the caller to remove elements from the underlying collection, something which is not possible with Enumerations. 34. What is the difference between HashSet and TreeSet ? The HashSet is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn). Garbage Collectors 35. What is the purpose of garbage collection in Java, and when is it used ? The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application, in order for the resources to be reclaimed and reused. 36. What does System.gc() and Runtime.gc() methods do ? These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time. 37. When is the finalize() called ? What is the purpose of finalization ? The finalize method is called by the garbage collector, just before releasing the object’s memory. It is normally advised to release resources held by the object inside the finalize method. 38. If an object reference is set to null, will the Garbage Collector immediately free the memory held by that object ? No, the object will be available for garbage collection in the next cycle of the garbage collector. 39. What is structure of Java Heap ? What is Perm Gen space in Heap ? The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector. 40. What is the difference between Serial and Throughput Garbage collector ? The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. On the other hand, the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors). 41. When does an Object becomes eligible for Garbage collection in Java ? A Java object is subject to garbage collection when it becomes unreachable to the program in which it is currently used. 42. Does Garbage collection occur in permanent generation space in JVM ? Garbage Collection does occur in PermGen space and if PermGen space is full or cross a threshold, it can trigger a full garbage collection. If you look carefully at the output of the garbage collector, you will find that PermGen space is also garbage collected. This is the reason why correct sizing of PermGen space is important to avoid frequent full garbage collections. Also check our article Java 8: PermGen to Metaspace. Exception Handling 43. What are the two types of Exceptions in Java ? Which are the differences between them ? Java has two types of exceptions: checked exceptions and unchecked exceptions. Unchecked exceptions do not need to be declared in a method or a constructor’s throws clause, if they can be thrown by the execution of the method or the constructor, and propagate outside the method or constructor boundary. On the other hand, checked exceptions must be declared in a method or a constructor’s throws clause. See here for tips on Java exception handling. 44. What is the difference between Exception and Error in java ? Exception and Error classes are both subclasses of the Throwable class. The Exception class is used for exceptional conditions that a user’s program should catch. The Error class defines exceptions that are not excepted to be caught by the user program. 45. What is the difference between throw and throws ? The throw keyword is used to explicitly raise a exception within the program. On the contrary, the throws clause is used to indicate those exceptions that are not handled by a method. Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. Finally, multiple exceptions are separated by a comma. 45. What is the importance of finally block in exception handling ? A finally block will always be executed, whether or not an exception is actually thrown. Even in the case where the catch statement is missing and an exception is thrown, the finally block will still be executed. Last thing to mention is that the finally block is used to release resources like I/O buffers, database connections, etc. 46. What will happen to the Exception object after exception handling ? The Exception object will be garbage collected in the next garbage collection. 47. How does finally block differ from finalize() method ? A finally block will be executed whether or not an exception is thrown and is used to release those resources held by the application. Finalize is a protected method of the Object class, which is called by the Java Virtual Machine (JVM) just before an object is garbage collected. Java Applets 48. What is an Applet ? A java applet is program that can be included in a HTML page and be executed in a java enabled client browser. Applets are used for creating dynamic and interactive web applications. 49. Explain the life cycle of an Applet. An applet may undergo the following states:Init: An applet is initialized each time is loaded. Start: Begin the execution of an applet. Stop: Stop the execution of an applet. Destroy: Perform a final cleanup, before unloading the applet.50. What happens when an applet is loaded ? First of all, an instance of the applet’s controlling class is created. Then, the applet initializes itself and finally, it starts running. 51. What is the difference between an Applet and a Java Application ? Applets are executed within a java enabled browser, but a Java application is a standalone Java program that can be executed outside of a browser. However, they both require the existence of a Java Virtual Machine (JVM). Furthermore, a Java application requires a main method with a specific signature, in order to start its execution. Java applets don’t need such a method to start their execution. Finally, Java applets typically use a restrictive security policy, while Java applications usually use more relaxed security policies. 52. What are the restrictions imposed on Java applets ? Mostly due to security reasons, the following restrictions are imposed on Java applets:An applet cannot load libraries or define native methods. An applet cannot ordinarily read or write files on the execution host. An applet cannot read certain system properties. An applet cannot make network connections except to the host that it came from. An applet cannot start any program on the host that’s executing it.53. What are untrusted applets ? Untrusted applets are those Java applets that cannot access or execute local system files. By default, all downloaded applets are considered as untrusted. 54. What is the difference between applets loaded over the internet and applets loaded via the file system ? Regarding the case where an applet is loaded over the internet, the applet is loaded by the applet classloader and is subject to the restrictions enforced by the applet security manager. Regarding the case where an applet is loaded from the client’s local disk, the applet is loaded by the file system loader. Applets loaded via the file system are allowed to read files, write files and to load libraries on the client. Also, applets loaded via the file system are allowed to execute processes and finally, applets loaded via the file system are not passed through the byte code verifier. 55. What is the applet class loader, and what does it provide ? When an applet is loaded over the internet, the applet is loaded by the applet classloader. The class loader enforces the Java name space hierarchy. Also, the class loader guarantees that a unique namespace exists for classes that come from the local file system, and that a unique namespace exists for each network source. When a browser loads an applet over the net, that applet’s classes are placed in a private namespace associated with the applet’s origin. Then, those classes loaded by the class loader are passed through the verifier.The verifier checks that the class file conforms to the Java language specification . Among other things, the verifier ensures that there are no stack overflows or underflows and that the parameters to all bytecode instructions are correct. 56. What is the applet security manager, and what does it provide ? The applet security manager is a mechanism to impose restrictions on Java applets. A browser may only have one security manager. The security manager is established at startup, and it cannot thereafter be replaced, overloaded, overridden, or extended. Swing 57. What is the difference between a Choice and a List ? A Choice is displayed in a compact form that must be pulled down, in order for a user to be able to see the list of all available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. 58. What is a layout manager ? A layout manager is the used to organize the components in a container. 59. What is the difference between a Scrollbar and a JScrollPane ? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. 60. Which Swing methods are thread-safe ? There are only three thread-safe methods: repaint, revalidate, and invalidate. 61. Name three Component subclasses that support painting. The Canvas, Frame, Panel, and Applet classes support painting. 62. What is clipping ? Clipping is defined as the process of confining paint operations to a limited area or shape. 63. What is the difference between a MenuItem and a CheckboxMenuItem ? The CheckboxMenuItem class extends the MenuItem class and supports a menu item that may be either checked or unchecked. 64. How are the elements of a BorderLayout organized ? The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. 65. How are the elements of a GridBagLayout organized ? The elements of a GridBagLayout are organized according to a grid. The elements are of different sizes and may occupy more than one row or column of the grid. Thus, the rows and columns may have different sizes. 66. What is the difference between a Window and a Frame ? The Frame class extends the Window class and defines a main application window that can have a menu bar. 67. What is the relationship between clipping and repainting ? When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting. 68. What is the relationship between an event-listener interface and an event-adapter class ? An event-listener interface defines the methods that must be implemented by an event handler for a particular event. An event adapter provides a default implementation of an event-listener interface. 69. How can a GUI component handle its own events ? A GUI component can handle its own events, by implementing the corresponding event-listener interface and adding itself as its own event listener. 70. What advantage do Java’s layout managers provide over traditional windowing systems ? Java uses layout managers to lay out components in a consistent manner, across all windowing platforms. Since layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems. 71. What is the design pattern that Java uses for all Swing components ? The design pattern used by Java for all Swing components is the Model View Controller (MVC) pattern. JDBC 72. What is JDBC ? JDBC is an abstraction layer that allows users to choose between databases. JDBC enables developers to write database applications in Java, without having to concern themselves with the underlying details of a particular database. 73. Explain the role of Driver in JDBC. The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each driver must provide implementations for the following classes of the java.sql package:Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver. 74. What is the purpose Class.forName method ? This method is used to method is used to load the driver that will establish a connection to the database. 75. What is the advantage of PreparedStatement over Statement ? PreparedStatements are precompiled and thus, their performance is much better. Also, PreparedStatement objects can be reused with different input values to their queries. 76. What is the use of CallableStatement ? Name the method, which is used to prepare a CallableStatement. A CallableStatement is used to execute stored procedures. Stored procedures are stored and offered by a database. Stored procedures may take input values from the user and may return a result. The usage of stored procedures is highly encouraged, because it offers security and modularity.The method that prepares a CallableStatement is the following: CallableStament.prepareCall(); 77. What does Connection pooling mean ? The interaction with a database can be costly, regarding the opening and closing of database connections. Especially, when the number of database clients increases, this cost is very high and a large number of resources is consumed.A pool of database connections is obtained at start up by the application server and is maintained in a pool. A request for a connection is served by a connection residing in the pool. In the end of the connection, the request is returned to the pool and can be used to satisfy future requests. Remote Method Invocation (RMI) 78. What is RMI ? The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object. Check some RMI Tips here. 79. What is the basic principle of RMI architecture ? The RMI architecture is based on a very important principle which states that the definition of the behavior and the implementation of that behavior, are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs. 80. What are the layers of RMI Architecture ? The RMI architecture consists of the following layers:Stub and Skeleton layer: This layer lies just beneath the view of the developer. This layer is responsible for intercepting method calls made by the client to the interface and redirect these calls to a remote RMI Service. Remote Reference Layer: The second layer of the RMI architecture deals with the interpretation of references made from the client to the server’s remote objects. This layer interprets and manages references made from clients to the remote service objects. The connection is a one-to-one (unicast) link. Transport layer: This layer is responsible for connecting the two JVM participating in the service. This layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.81. What is the role of Remote Interface in RMI ? The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. A class that implements a remote interface should declare the remote interfaces being implemented, define the constructor for each remote object and provide an implementation for each remote method in all remote interfaces. 82. What is the role of the java.rmi.Naming Class ? The java.rmi.Naming class provides methods for storing and obtaining references to remote objects in the remote object registry. Each method of the Naming class takes as one of its arguments a name that is a String in URL format. 83. What is meant by binding in RMI ? Binding is the process of associating or registering a name for a remote object, which can be used at a later time, in order to look up that remote object. A remote object can be associated with a name using the bind or rebind methods of the Naming class. 84. What is the difference between using bind() and rebind() methods of Naming Class ? The bind method bind is responsible for binding the specified name to a remote object, while the rebind method is responsible for rebinding the specified name to a new remote object. In case a binding exists for that name, the binding is replaced. 85. What are the steps involved to make work a RMI program ? The following steps must be involved in order for a RMI program to work properly:Compilation of all source files. Generatation of the stubs using rmic. Start the rmiregistry. Start the RMIServer. Run the client program.86. What is the role of stub in RMI ? A stub for a remote object acts as a client’s local representative or proxy for the remote object. The caller invokes a method on the local stub, which is responsible for executing the method on the remote object. When a stub’s method is invoked, it undergoes the following steps:It initiates a connection to the remote JVM containing the remote object. It marshals the parameters to the remote JVM. It waits for the result of the method invocation and execution. It unmarshals the return value or an exception if the method has not been successfully executed. It returns the value to the caller.87. What is DGC ? And how does it work ? DGC stands for Distributed Garbage Collection. Remote Method Invocation (RMI) uses DGC for automatic garbage collection. Since RMI involves remote object references across JVM’s, garbage collection can be quite difficult. DGC uses a reference counting algorithm to provide automatic memory management for remote objects. 88. What is the purpose of using RMISecurityManager in RMI ? RMISecurityManager provides a security manager that can be used by RMI applications, which use downloaded code. The class loader of RMI will not download any classes from remote locations, if the security manager has not been set. 89. Explain Marshalling and demarshalling. When an application wants to pass its memory objects across a network to another host or persist it to storage, the in-memory representation must be converted to a suitable format. This process is called marshalling and the revert operation is called demarshalling. 90. Explain Serialization and Deserialization. Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes and includes the object’s data, as well as information about the object’s type, and the types of data stored in the object. Thus, serialization can be seen as a way of flattening objects, in order to be stored on disk, and later, read back and reconstituted. Deserialisation is the reverse process of converting an object from its flattened state to a live object. Servlets 91. What is a Servlet ? The servlet is a Java programming language class used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol. 92. Explain the architechure of a Servlet. The core abstraction that must be implemented by all servlets is the javax.servlet.Servlet interface. Each servlet must implement it either directly or indirectly, either by extending javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet. Finally, each servlet is able to serve multiple requests in parallel using multithreading. 93. What is the difference between an Applet and a Servlet ? An Applet is a client side java program that runs within a Web browser on the client machine. On the other hand, a servlet is a server side component that runs on the web server.An applet can use the user interface classes, while a servlet does not have a user interface. Instead, a servlet waits for client’s HTTP requests and generates a response in every request. 94. What is the difference between GenericServlet and HttpServlet ? GenericServlet is a generalized and protocol-independent servlet that implements the Servlet and ServletConfig interfaces. Those servlets extending the GenericServlet class shall override the service method. Finally, in order to develop an HTTP servlet for use on the Web that serves requests using the HTTP protocol, your servlet must extend the HttpServlet instead. Check Servlet examples here. 95. Explain the life cycle of a Servlet. On every client’s request, the Servlet Engine loads the servlets and invokes its init methods, in order for the servlet to be initialized. Then, the Servlet object handles all subsequent requests coming from that client, by invoking the service method for each request separately. Finally, the servlet is removed by calling the server’s destroy method. 96. What is the difference between doGet() and doPost() ? doGET: The GET method appends the name-value pairs on the request’s URL. Thus, there is a limit on the number of characters and subsequently on the number of values that can be used in a client’s request. Furthermore, the values of the request are made visible and thus, sensitive information must not be passed in that way. doPOST: The POST method overcomes the limit imposed by the GET request, by sending the values of the request inside its body. Also, there is no limitations on the number of values to be sent across. Finally, the sensitive information passed through a POST request is not visible to an external client. 97. What is meant by a Web Application ? A Web application is a dynamic extension of a Web or application server. There are two types of web applications: presentation-oriented and service-oriented. A presentation-oriented Web application generates interactive web pages, which contain various types of markup language and dynamic content in response to requests. On the other hand, a service-oriented web application implements the endpoint of a web service. In general, a Web application can be seen as a collection of servlets installed under a specific subset of the server’s URL namespace. 98. What is a Server Side Include (SSI) ? Server Side Includes (SSI) is a simple interpreted server-side scripting language, used almost exclusively for the Web, and is embedded with a servlet tag. The most frequent use of SSI is to include the contents of one or more files into a Web page on a Web server. When a Web page is accessed by a browser, the Web server replaces the servlet tag in that Web page with the hyper text generated by the corresponding servlet. 99. What is Servlet Chaining ? Servlet Chaining is the method where the output of one servlet is sent to a second servlet. The output of the second servlet can be sent to a third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client. 100. How do you find out what client machine is making a request to your servlet ? The ServletRequest class has functions for finding out the IP address or host name of the client machine. getRemoteAddr() gets the IP address of the client machine and getRemoteHost() gets the host name of the client machine. See example here. 101. What is the structure of the HTTP response ? The HTTP response consists of three parts:Status Code: describes the status of the response. It can be used to check if the request has been successfully completed. In case the request failed, the status code can be used to find out the reason behind the failure. If your servlet does not return a status code, the success status code, HttpServletResponse.SC_OK, is returned by default. HTTP Headers: they contain more information about the response. For example, the headers may specify the date/time after which the response is considered stale, or the form of encoding used to safely transfer the entity to the user. See how to retrieve headers in Servlet here. Body: it contains the content of the response. The body may contain HTML code, an image, etc. The body consists of the data bytes transmitted in an HTTP transaction message immediately following the headers.102. What is a cookie ? What is the difference between session and cookie ? A cookie is a bit of information that the Web server sends to the browser. The browser stores the cookies for each Web server in a local file. In a future request, the browser, along with the request, sends all stored cookies for that specific Web server.The differences between session and a cookie are the following:The session should work, regardless of the settings on the client browser. The client may have chosen to disable cookies. However, the sessions still work, as the client has no ability to disable them in the server side. The session and cookies also differ in the amount of information the can store. The HTTP session is capable of storing any Java object, while a cookie can only store String objects.103. Which protocol will be used by browser and servlet to communicate ? The browser communicates with a servlet by using the HTTP protocol. 104. What is HTTP Tunneling ? HTTP Tunneling is a technique by which, communications performed using various network protocols are encapsulated using the HTTP or HTTPS protocols. The HTTP protocol therefore acts as a wrapper for a channel that the network protocol being tunneled uses to communicate. The masking of other protocol requests as HTTP requests is HTTP Tunneling. 105. What’s the difference between sendRedirect and forward methods ? The sendRedirect method creates a new request, while the forward method just forwards a request to a new target. The previous request scope objects are not available after a redirect, because it results in a new request. On the other hand, the previous request scope objects are available after forwarding. FInally, in general, the sendRedirect method is considered to be slower compare to the forward method. 106. What is URL Encoding and URL Decoding ? The URL encoding procedure is responsible for replacing all the spaces and every other extra special character of a URL, into their corresponding Hex representation. In correspondence, URL decoding is the exact opposite procedure. JSP 107. What is a JSP Page ? A Java Server Page (JSP) is a text document that contains two types of text: static data and JSP elements. Static data can be expressed in any text-based format, such as HTML or XML. JSP is a technology that mixes static content with dynamically-generated content. See JSP example here. 108. How are the JSP requests handled ? On the arrival of a JSP request, the browser first requests a page with a .jsp extension. Then, the Web server reads the request and using the JSP compiler, the Web server converts the JSP page into a servlet class. Notice that the JSP file is compiled only on the first request of the page, or if the JSP file has changed.The generated servlet class is invoked, in order to handle the browser’s request. Once the execution of the request is over, the servlet sends a response back to the client. See how to get Request parameters in a JSP. 109. What are the advantages of JSP ? The advantages of using the JSP technology are shown below:JSP pages are dynamically compiled into servlets and thus, the developers can easily make updates to presentation code. JSP pages can be pre-compiled. JSP pages can be easily combined to static templates, including HTML or XML fragments, with code that generates dynamic content. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax. Developers can make logic changes at the component level, without editing the individual pages that use the application’s logic.110. What are Directives ? What are the different types of Directives available in JSP ? Directives are instructions that are processed by the JSP engine, when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >.The different types of directives are shown below:Include directive: it is used to include a file and merges the content of the file with the current page. Page directive: it is used to define specific attributes in the JSP page, like error page and buffer. Taglib: it is used to declare a custom tag library which is used in the page.111. What are JSP actions ? JSP actions use constructs in XML syntax to control the behavior of the servlet engine. JSP actions are executed when a JSP page is requested. They can be dynamically inserted into a file, re-use JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.Some of the available actions are listed below:jsp:include – includes a file, when the JSP page is requested. jsp:useBean – finds or instantiates a JavaBean. jsp:setProperty – sets the property of a JavaBean. jsp:getProperty – gets the property of a JavaBean. jsp:forward – forwards the requester to a new page. jsp:plugin – generates browser-specific code.112. What are Scriptlets ? In Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between these tags, a user can add any valid scriplet. 113. What are Decalarations ? Declarations are similar to variable declarations in Java. Declarations are used to declare variables for subsequent use in expressions or scriptlets. To add a declaration, you must use the sequences to enclose your declarations. 114. What are Expressions ? A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client, by the web server. Expressions are defined between <% = and %> tags. 115. What is meant by implicit objects and what are they ? JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. A developer can call them directly, without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.The following objects are considered implicit in a JSP page:application page request response session exception out config pageContextStill with us? Wow, that was a huge article about different types of questions that can be used in a Java interview. If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers! Also, check out JCG Academy for more advanced training! So, what other Java interview questions are there? Let us know in the comments and we will include them in the article! Happy coding! ...

How Agile is a Scrum team?

Most teams I meet today are agile. Or, so they proclaim to be. All of these teams do Scrum, and that makes them agile. Doesn’t it? If I look back at the 12 practices the Agile Manifesto is build on (short: the Agile practices) I conclude that Scrum values a subset: the planning game, on-site customer, small releases and whole team. Yet most of the teams doing Scrum that I meet have no customer on-site, although the teams do value this practice. Furthermore I mostly see a formal separation of developers and QA, and more often than not these teams use large releases (more than a few months). On the up side, most teams use Continuous Integration and have a set of coding standards, often formal. The average of applying 3 out of the 12 Agile practices makes me wonder. Are these teams actually agile? Or maybe they are just a “little agile”. Is that a thing? Agile Principles Let’s take a look at the Principles behind the Agile Manifesto. The number one priority is “to satisfy the customer through early and continuous delivery of valuable software”. Closely followed by the importance to (even late in development) embrace changing requirements and the notion that working software is the primary measure of progress. These may seem to be supported by the planning game with user stories, doing the most valuable story first. That way the customer gets the most value out of each sprint, right? While that’s true, I believe there’s more to it. While valuable software is very important, I think the key is in the early and continuous delivery of software. We add value to software by changing and extending it. This is what the planning game and user stories won’t help us with. But changing software is highly valued by the Agile Principles. Rest of the Agile Practices And therefore there are Agile Practices that support us in changing software, enabling us to embrace change of requirements. These practices include automation of acceptance tests, test-driven development, pair programming, simple design and refactoring (not in any specific order). I wonder how well Scrum teams can keep up the agile principles if they don’t follow any other of these practices. I’ve seen teams respond to new requirements by demanding a “refactor sprint” to clean up the mess they made. Because there was no way to incorporate the changes otherwise. I’ve been on such teams years ago. I won’t state that it’s impossible for teams to continuously deliver valuable software without following most of the agile practices. But I do wonder how they at all could. I mean, without simple design and constantly keeping the code clean, how well can code be changed, even in a few months from creating it? What raises a flag for a broker feature when lacking stable unit and acceptance test suites? So without most of the agile practices, can you really get into a stable and continuous delivery of value? Scrum I don’t think Scrum is to blame here. Don’t get me wrong. I like Scrum. Scrum mostly embodies the planning and management rules of Extreme Programming (XP). I believe it’s thanks to Scrum that much of the planning and management practices have made their way into mainstream today. It’s just because Scrum doesn’t include the other Agile practices many folks doing Scrum think that those are somehow unimportant. The most successful teams I’ve seen are all doing most, if not all, of the other Agile practices as well. This is also totally possible for a Scrum team. You’re mileage may vary Over the past years I’ve been practicing different ways to write software, but every time I got back to the agile practices as I find them to work best. You’re mileage may vary, of course. If you use different practices that even better support the Agile principles I would love to hear about them and try them myself.Reference: How Agile is a Scrum team? from our JCG partner Bart Bakker at the Software Craft blog....

Effective learning techniques for software craftsmen

Go in one ear and out the other Programming languages, operating systems, SQL, NoSQL, web frameworks, Spring, Java EE, HTML, JavaScript, Agile methodologies , you name it. A developer must know a ridiculous amount of things to become effective. There’s no wonder many of us are struggling to keep pace with the ever-changing programming landscape. When you’re a kid, doing stuff is the most natural way of learning, but then you go to school and you’re brainwashed into thinking that reading is the only way of studying. Become an active learner Ever since I started writing this blog I began to question my old ways of learning. I used to be a passive learner, reading books, articles or watching videos. But I realized this is not working the way it should, so I started looking for alternatives. Edgar Dale‘s evaluated the most common learning techniques and came up with the famous Cone of experience. Basically, if you want to be a better developer you need to become an active learner. Writing a blog Until you start writing, you don’t really appreciate the actual effort put into coming up with a decent article. Writing down your findings not only helps the community, it helps your too. The writing process is going to teach you more about a given subject. You want to publish quality articles and the upcoming critique is going to be a good motivator. Contributing to your favourite frameworks The customer doesn’t want you to spend his money on writing frameworks, so your company makes use of high-quality open source frameworks. This is cost effective, but someone has to write those frameworks after all. It’s time for our employers to realize that contributing is a form of investment. Getting involved is the best way to master a given technology. Passionate developers will allocate their spare time in this purpose, but it doesn’t always have to be that way. What if all employers will allocate developers some hours for contributing to those open source projects they’ve been employing? You’ll meet other great guys with solid developing skills and this is probably a cheaper way of training your developers. Contributing to your own frameworks If you want developers to appreciate all the effort put into managing, testing or marketing, the best way is to have them lead their own open source project. Starting your own GitHub project is going to teach you a lot about Product ownership, software design or marketing techniques. Writing frameworks is so much different than the current enterprise developing experience. You need to pay extra attention to your framework programming usability for your adopters to spend the minimum amount of time while employing your software. Conclusion Getting involved is the true way of the software craftsman. A pragmatic programmer never bashes his tools, giving a helping hand instead. Helping building a better software community is the most effective way of becoming a better developer.Reference: Effective learning techniques for software craftsmen from our JCG partner Vlad Mihalcea at the Vlad Mihalcea’s Blog blog....

Common Misconceptions About Java

Java is the most widely used language in the world ([citation needed]), and everyone has an opinion about it. Due to it being mainstream, it is usually mocked, and sometimes rightly so, but sometimes the criticism just doesn’t touch reality. I’ll try to explain my favorite 5 misconceptions about Java.              Java is slow – that might have been true for Java 1.0, and initially may sounds logical, since java is not compiled to binary, but to bytecode, which is in turn interpreted. However, modern versions of the JVM are very, very optimized (JVM optimizations is a topic worth not just an article, but a whole book) and this is no longer remotely true. As noted here, Java is even on-par with C++ in some cases. And it is certainly not a good idea to make a joke about Java being slow if you are a Ruby or PHP developer. Java is too verbose – here we need to split the language from the SDK and from other libraries.There is some verbosity in the JDK (e.g. java.io), which is: 1. easily overcome with de-facto standard libraries like guava 2. a good thing As for language verbosity, the only reasonable point were anonymous classes. Which are no longer an issue in Java 8 with the the functional additions. Getters and setters, Foo foo = new Foo() instead of using val – that is (possibly) boilerplate, but it’s not verbose – it doesn’t add conceptual weight to the code. It doesn’t take more time to write, read or understand. Other libraries – it is indeed pretty scary to see a class like AbstractCommonAsyncFacadeFactoryManagerImpl. But that has nothing to do with Java. It can be argued that sometimes these long names make sense, it can also be argued that they are as complex because the underlying abstraction is unnecessarily complicated, but either way, it is a design decision taken per-library, and nothing that the language or the SDK impose per-se. It is common to see overengineered stuff, but Java in no way pushes you in that direction – stuff can be done in a simple way with any language. You can certainly have AbstractCommonAsyncFacadeFactoryManagerImpl in Ruby, just there wasn’t a stupid architect that thought it’s a good idea and who uses Ruby. If “big, serious, heavy” companies were using Ruby, I bet we’d see the same.Enterprise Java frameworks are bloatware – that was certainly true back in 2002 when EJB 2 was in use (or “has been”, I’m too young to remember). And there are still some overengineered and bloated application servers that you don’t really need. The fact that people are using them is their own problem. You can have a perfectly nice, readable, easy to configure and deploy web application with a framework like Spring, Guice or even CDI; with a web framework like Spring-MVC, Play, Wicket, and even the latest JSF. Or even without any framework, if you feel like you don’t want to reuse the evolved-through-real-world-use frameworks. You can have an application using a message queue, a NoSQL and a SQL database, Amazon S3 file storage, and whatnot, without any accidental complexity. It’s true that people still like to overeingineer stuff, and add a couple of layers where they are not needed, but the fact that frameworks give you this ability doesn’t mean they make you do it. For example, here’s an application that crawls government documents, indexes them, and provides a UI for searching and subscribing. Sounds sort-of simple, and it is. It is written in Scala (in a very java way), but uses only java frameworks – spring, spring-mvc, lucene, jackson, guava. I guess you can start maintaining pretty fast, because it is straightforward. You can’t prototype quickly with Java – this is sort-of related to the previous point – it is assumed that working with Java is slow, and that’s why if you are a startup, or a weekend/hackathon project, you should use Ruby (with Rails), Python, Node JS or anything else that allows you to quickly prototype, to save & refresh, to painlessly iterate. Well, that is simply not true, and I don’t know even where it comes from. Maybe from the fact that big companies with heavy processes use Java, and so making a java app is taking more time. And Save-and-Refresh might look daunting to a beginner, but anyone who has programmed in Java (for the web) for a while, has to know a way to automate that (otherwise he’s a n00b, right?). I’ve summarized the possible approaches, and all of them are mostly OK. Another example here (which may be used as an example for the above point as well) – I made did this project for verifying secure password storage of websites within a weekend + 1 day to fix stuff in the evening. Including the security research. Spring-MVC, JSP templates, MongoDB. Again – quick and easy. You can do nothing in Java without an IDE – of course you can – you can use notepad++, vim, emacs. You will just lack refactoring, compile-on-save, call hierarchies. It would be just like programming in PHP or Python or javascript. The IDE vs Editor debate is a long one, but you can use Java without an IDE. It just doesn’t make sense to do so, because you get so much more from the IDE than from a text editor + command line tools.You may argue that I’m able to write nice and simple java applications quickly because I have a lot of experience, I know precisely which tools to use (and which not) and that I’m of some rare breed of developers with common sense. And while I’ll be flattered by that, I am no different than the good Ruby developer or the Python guru you may be. It’s just that java is too widespread to have only good developers and tools. if so many people were using other language, then probably the same amount of crappy code would’ve been generated. (And PHP is already way ahead even with less usage). I’m the last person not to laugh on jokes about Java, and it certainly isn’t the silver bullet language, but I’d be happier if people had less misconceptions either because of anecdotal evidence, or due to previous bad experience a-la “I hate Java since my previous company where the project was very bloated”. Not only because I don’t like people being biased, but because you may start your next project with a language that will not work, just because you’ve heard “Java is bad”.Reference: Common Misconceptions About Java from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog....

Using Android Location API in Weather App – Search city

In this post I would like to describe how to search a city using openweathermap to get weather conditions. There are two way we can use to find a city:Using name pattern Using geographic coordinates (Android Location API)We will introduce, moreover, some concepts about Android location API and Location-based service.   Searching city by name In this kind of search, an user inserts a part of city name and the app will show all the possible result matching the pattern. From the UI perspective, we want to obtain something like the image shown below:  As first step, we can use EditText so that the user can insert the city name: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >.... <EditText android:id="@+id/cityEdtText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="5dp" android:imeOptions="actionSearch" android:inputType="text" > <requestFocus /> </EditText> ....<ListView android:id="@+id/cityList" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txt1" android:layout_marginTop="3dp"/></RelativeLayout> Notice that at line 13, we used imeOptions with “actionSearch” value to specify search action when user completes inserting the city name pattern. Now in the Activity that holds this layout we have: final EditText edt = (EditText) findViewById(R.id.cityEdtText);edt.setOnEditorActionListener(new TextView.OnEditorActionListener() {@Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { bar.setVisibility(View.VISIBLE); JSONSearchTask task = new JSONSearchTask(); String pattern = edt.getEditableText().toString(); task.execute(new String[]{pattern}); return true; }return false; } }); So when user clicks on search icon, we starts searching for matching city names and at the end we will populate a ListView (line 18) . As you can notice, we start an AsyncTask, because the search operation can require quite long time and we don’t want to have ANR problems. Now it is time to implement the logic that calls the remote openweathermap service and retrieve the cities. We know from API that the URL to call is: http://api.openweathermap.org/data/2.5/find?mode=json&type=like&q=...&cnt=10 where after q we will add our pattern name and cnt represents the number of items we want to get (in our case we want 10 results at maximum). Once we have the data, we parse it. We look for list tag that holds the result and for each item in the result we look for name tag that holds the name, the id and the country. The parser is very simple: public static List<City> getCityList(String data) throws JSONException { JSONObject jObj = new JSONObject(data); JSONArray jArr = jObj.getJSONArray("list"); List<City> cityList = new ArrayList<City>(); for (int i=0; i < jArr.length(); i++) { JSONObject obj = jArr.getJSONObject(i); String name = obj.getString("name"); String id = obj.getString("id"); JSONObject sys = obj.getJSONObject("sys"); String country = sys.getString("country"); City c = new City(id,name,country); cityList.add(c); } return cityList; }..and finally we populate the ListView to show the results to the user. This happen in  onPostExecute method of the AsyncTask. Notice that you can create a custom Adapter to show this information or you can use a standard Adapter. Search city using geographic coordinates: Android Location API Another way to look for the city is using the current user position. We can use Location based service to find the current device position using GPS or WI-FI or cell network. There are two main element when implementing Location based service:Location Manager that is the entry point to the Location based service Location Provider representing the location technology used to find the device positionThe first step is getting the LocationManager reference. This is a system service, then we can use: LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); once we have our Location Manager reference we can find the provider. In our case, we don’t want to specify a specific provider (like GPS for example) but let the system find the best matching the search criteria we set: private static Criteria searchProviderCriteria = new Criteria();// Location Criteria static { searchProviderCriteria.setPowerRequirement(Criteria.POWER_LOW); searchProviderCriteria.setAccuracy(Criteria.ACCURACY_COARSE); searchProviderCriteria.setCostAllowed(false); } and then we are ready to get the provider: String provider = locManager.getBestProvider(searchProviderCriteria, true); and: Location loc = locManager.getLastKnownLocation(provider); Now we have to check if the location is null or is too old, in this case we get a new position: if (loc == null || (SystemClock.elapsedRealtime() - loc.getTime()) > timeOut) { // We request another update Location Log.d("SwA", "Request location"); locManager.requestSingleUpdate(provider, locListener, null); } else { JSONSearchTask task = new JSONSearchTask(); task.execute(new Location[]{loc}); } otherwise we simply call the service to get the city. Notice at line 4, that we need a listener that implements some callback methods, that will be called when the current position is available: private LocationListener locListener = new LocationListener() {@Override public void onStatusChanged(String provider, int status, Bundle extras) { }@Override public void onProviderEnabled(String provider) { }@Override public void onProviderDisabled(String provider) { }@Override public void onLocationChanged(Location location) { Log.d("SwA", "Location changed!"); String sLat = "" + location.getLatitude(); String sLon = "" + location.getLongitude(); Log.d("SwA", "Lat ["+sLat+"] - sLong ["+sLon+"]");LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locManager.removeUpdates(locListener); JSONSearchTask task = new JSONSearchTask(); task.execute(new Location[]{location}); } }; The last step is creating the URL that will be called to retrieve the city from the geographic coordinates. In this case the url to call is: http://api.openweathermap.org/data/2.5/find?lat=%lat%&lon=%lon% where the %lat% and &lon% will be substituted by the real value extracted from the current position. Using emulator to test the app The last step is testing the app passing the coordinates. We can use DDMSDDMS and pass the coordinates:  Please notice that you should separate the decimal part according to your language and number format. Another way is using telnet iphost port and when connected send geo fix <longitude value> <latitude value>Reference: Using Android Location API in Weather App – Search city from our JCG partner Francesco Azzola at the Surviving w/ Android blog....

Consume Webservice in Android using intentService

In this post, I will explain how to consume Restful Webservice using IntentService. We know we can consume a Webservice directly in the UI using for example Volley lib or a simple Http client, but there are some cases when we prefer to consume a Webservice in an Android Service. We know that Android Service has a “longer” life than an Android Activity and if we want a task is completed even if the app UI is no longer available we should use a Service. We can consider for example the download scenario: let’s suppose we want to download some information from a remote server; we can do it in the UI (i.e Activity) but if the user, for example, moves to another app the download will be interrupted. If we want to be sure that the download continues even if the app isn’t anymore active we can use Service. IntentService description When we want to consume a Webservice, we have to be aware that the time required to contact the server and get the response can be quite long. Even if we execute this logic is a separate service, the service itself runs in the main thread, so that the calling activity can lag, waiting for the response from the service, and the OS can kill it showing the annoying ANR message. We can avoid this problem handling a separate thread inside the service, but Android SDK provides a specialized class, derived from the Service class, called IntentService defined as (from Android API docs): “IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.This “work queue processor” pattern is commonly used to offload tasks from an application’s main thread.” Considering that the heavy work is made in a separate thread we don’t know when it will finish and the calling Activity is unaware of it. We will describe how to get back the information as the service retrieved data from the remote Webservice. Creating the IntentService As example we will use Yahoo! Finance Service to retrieve the current Ask and Bid value for a Stock. At the end we will build an app like this:  The first step is creating a service: public class QuoteService extends IntentService {@Override protected void onHandleIntent(Intent intent) { // Here we do the heavy work } }At line 4, in onHandleIntent we do the “heavy work”, so we call the remote Webservice and parse the response. In this case we can simply use XmlPullParser to parse the data: // Here we retrieve the stock quote using Yahoo! Finance Log.d("Srv", "Get stock"); String url = YAHOO_FINANCE_URL.replaceAll("#sym#", stock.getSymbol()); try { HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection(); con.setRequestMethod("GET"); con.connect(); InputStream is = con.getInputStream();// Start parsing XML XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(is, null); int event = parser.getEventType(); String tagName = null; String currentTag = null; Stock stockResult = new Stock();while (event != XmlPullParser.END_DOCUMENT) { tagName = parser.getName(); Log.d("Srv", "Tag:" + tagName); if (event == XmlPullParser.START_TAG) { currentTag = tagName; } else if (event == XmlPullParser.TEXT) { if ("ASK".equalsIgnoreCase(currentTag)) // else if ("BID".equalsIgnoreCase(currentTag)) { // } }event = parser.next();}} catch (Exception e) { e.printStackTrace(); } Then we define our service in the Manifest.xml: <service android:name=".QuoteService" /> Activity: Webservice client The next step is creating the client activity that invokes the service. We are using an IntentService then the calling Activity calls the service and then forget it. The activity is quite trivial, because as soon as the user clicks “Get quote!” button we invoke the service using: startService(service_intent); Anyway, there are two aspects we should consider:How we pass the data to the service How we get the data back from the service and show the information in UITo pass data to the service we can create a simple java class that holds the stock symbol and the values we want to be filled by the service as we get the response. Our class should be a Parcelable class: public class Stock implements Parcelable {private String symbol; private double askValue; private double bidValue;public Stock() {}public Stock(String symbol, double askValue, double bidValue) { this.symbol = symbol; this.askValue = askValue; this.bidValue = bidValue; }// get and set method@Override public void writeToParcel(Parcel dest, int flags) { // We write the stock information in the parcel dest.writeString(symbol); dest.writeDouble(askValue); dest.writeDouble(bidValue); }public static final Creator<Stock> CREATOR = new Creator<Stock>() {@Override public Stock createFromParcel(Parcel source) { Stock stock = new Stock(); stock.setSymbol(source.readString()); stock.setAskValue(source.readDouble()); stock.setBidValue(source.readDouble()); return stock; }@Override public Stock[] newArray(int size) { return new Stock[0]; } };@Override public int describeContents() { return 0; } } At line 18 and 25, we implement the two methods required to marshal and unmarshal our class. Retrieve data from service using ResultReceiver Another interesting aspect is how we can get the values back from the IntentService. As we, already, know the calling activity doesn’t wait for the result, so we have to find another way. Generally speaking there are different ways to solve this problem, in this post I will explain how to use ResultReceiver. This method is quite simple and elegant in my opinion. The first step is creating a class that extends ResultReceiver, that we call QuoteServiceReceiver: public class QuoteServiceReceiver extends ResultReceiver {private Listener listener;public QuoteServiceReceiver(Handler handler) { super(handler); }public void setListener(Listener listener) { this.listener = listener; }@Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (listener != null) listener.onReceiveResult(resultCode, resultData); }public static interface Listener { void onReceiveResult(int resultCode, Bundle resultData); }} This class is very simple. At line 19 we define an interface that the calling activity has to implement to get notified when the data isavailable. In this interface we define a Bundle that holds the data retrieved. Then at line 14 we override the onReceiveResult and call our callback method defined in the previous interface. From the client point of view (so our Activity) we simply have to implements the interface defined and pass the QuoteServiceReceiver to the IntentService: private Intent createCallingIntent(Stock stock) { Intent i = new Intent(this, QuoteService.class); QuoteServiceReceiver receiver = new QuoteServiceReceiver(new Handler()); receiver.setListener(this); i.putExtra("rec", receiver); i.putExtra("stock", stock); return i; } and when we call the service: startService(createCallingIntent(stock)); ..and in the callback method: @Override public void onReceiveResult(int resultCode, Bundle resultData) { Stock stock = resultData.getParcelable("stock"); Log.d("Srv", "Stock ["+stock+"]");askValue.setText("" + stock.getAskValue()); bidValue.setText("" + stock.getBidValue()); } ..and here we update the UI, with the data received. In the service that consumes the remote Webservice: @Override protected void onHandleIntent(Intent intent) {Stock stock = intent.getParcelableExtra("stock"); final ResultReceiver rec = (ResultReceiver) intent.getParcelableExtra("rec"); .... // When data is ready if ("BID".equalsIgnoreCase(currentTag)) { stockResult.setBidValue(Double.parseDouble(parser.getText())); Bundle b = new Bundle(); b.putParcelable("stock", stockResult); rec.send(0, b); } .... }Source code available @ githubReference: Consume Webservice in Android using intentService from our JCG partner Francesco Azzola at the Surviving w/ Android blog....

Spring Test Context Caching + AspectJ @Transactional + Ehcache pain

Are you using AspectJ @Transactionals and Spring? Do you have multiple SessionFactory’s maybe one for an embedded database for unit testing and one for the real database for integration testing? Are you getting one of these exceptions?org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.service.UnknownServiceException: Unknown service requestedorjava.lang.NullPointerException at net.sf.ehcache.Cache.isKeyInCache(Cache.java:3068) at org.hibernate.cache.ehcache.internal.regions.EhcacheDataRegion.contains(EhcacheDataRegion.java:223)Then you are running in to a problem where multiple, cached application contexts are stepping on each other. This blog post will describe some strategies to deal with the problems that we have encountered. Background Spring’s Text Context framework by default tries to minimize the number of times the spring container has to start by caching the containers. If you are running multiple tests that all use the same configuration, then you will only have to create the container once for all the tests instead of creating it before each test. If you have 1000′s of tests and the container takes 10-15 seconds to startup, this makes a real difference in build/test time. This only works if everyone (you and all of the libraries that you use) avoid static fields (global state), and unfortunately there are places where this is difficult/impossible to avoid — even spring violates this! A few places that have caused us problems:Spring AspectJ @Transactional support EhCache cache managersAspects are singletons by design. Spring uses this to place a reference to the BeanFactory as well as the PlatformTransactionManager. If you have multiple containers each with their “own” AnnotationTransactionAspect, they are in fact sharing the AnnotationTransactionAspect and whichever container starts up last is the “winner” causing all kinds of unexpected hard to debug problems. Ehcache is also a pain here. The ehcache library maints a static list of all of the cache managers that it has created in the VM. So if you want to use multiple containers, they will all share a reference to the same cache. Spring Test gives you a mechanism to indicate that this test has “dirtied” the container and that it needs to be created. This translates to destroying the container after the test class is finished. This is fine, but if your container has objects that are shared by the other containers, then destroying that shared object breaks the other containers. Solutions The easiest solution is to basically disable the application context caching entirely. This can be done simply by placing @DirtiesContext on every test or (better) you probably should use super classes (“abstract test fixtures”) to organize your tests anyways, in which case just add @DirtiesContext on the base class. Unfortunately you also lose all of the benefit of caching and your build times will increase. There is no general mechanism for the spring container to “clean itself up”, because this sharing of state across container is certainly an anti-pattern. The fact that they themselves do it (AnnotationTransactionAspect, EhCacheManagerFactoryBean.setShared(true), etc.) is an indication that perhaps they should add some support. If you want to keep caching, then step 1 is making sure that you don’t use any “static field” singletons in your code. Also make sure that any external resources that you write to are separated so that multiple containers can co-exist in the same JVM. To address the AspectJ problem, the best solution that I have found is to create a TestExecutionListener that “resets” the AnnotationTransactionAspect to point to the correct bean factory and PTM before test execution. The code for such a listener is in this gist. To then use the listener you put @TestListeners on your base class test fixture so that all tests run with the new listener. Note that when you use the @TestListeners annotation you then have to specify all of the execution listeners, including the existing Spring ones. There is an example in the gist. The workaround for Ehcache is to not allow CacheManager instances to be shared between containers. To do this, you have to ensure that the cache managers all have unique names. This is actually pretty easy to configure. @org.springframework.context.annotation.Configuration public class CacheBeans {private static final AtomicInteger cacheCounter = new AtomicInteger(0); @Bean public EhCacheManagerFactoryBean ecmfb() { EhCacheManagerFactoryBean ecmfb = new EhCacheManagerFactoryBean(); // cannot share the cache managers ecmfb.setShared(false); // if you are using ehcache.xml on the classpath then there's nothing more to do than just make it // a unique name. If you are using a different config file then use ecmfb.setConfigLocation() ecmfb.setCacheManagerName("ehCache-" + cacheCounter.incrementAndGet()); return ecmfb; } // more @Bean defs } Related Issues Here are some links to spring jira issues covering this problem: https://jira.spring.io/browse/SPR-6121 https://jira.spring.io/browse/SPR-6353Reference: Spring Test Context Caching + AspectJ @Transactional + Ehcache pain from our JCG partner Steve Ash at the Many Cups of Coffee blog....

Apache CXF 3.0: JAX-RS 2.0 and Bean Validation 1.1 finally together

The upcoming release 3.0 (currently in milestone 2 phase) of the great Apache CXF framework is bringing a lot of interesting and useful features, getting closer to deliver full-fledged JAX-RS 2.0 support. One of those features, a long-awaited by many of us, is the support of Bean Validation 1.1: easy and concise model to add validation capabilities to your REST services layer. In this blog post we are going to look how to configure Bean Validation 1.1 in your Apache CXF projects and discuss some interesting use cases. To keep this post reasonably short and focused, we will not discuss the Bean Validation 1.1 itself but concentrate more on integration with JAX-RS 2.0 resources (some of the bean validation basics we have already covered in the older posts). At the moment, Hibernate Validator is the de-facto reference implementation of Bean Validation 1.1 specification, with the latest version being 5.1.0.Final and as such it will be the validation provider of our choice (Apache BVal project at the moment supports only Bean Validation 1.0). It is worth to mention that Apache CXF is agnostic to implementation and will work equally well either with Hibernate Validator or Apache BVal once released. We are going to build a very simple application to manage people. Our model consists of one single class named Person. package com.example.model;import javax.validation.constraints.NotNull;import org.hibernate.validator.constraints.Email;public class Person { @NotNull @Email private String email; @NotNull private String firstName; @NotNull private String lastName;public Person() { }public Person( final String email ) { this.email = email; }public String getEmail() { return email; }public void setEmail( final String email ) { this.email = email; }public String getFirstName() { return firstName; }public String getLastName() { return lastName; }public void setFirstName( final String firstName ) { this.firstName = firstName; }public void setLastName( final String lastName ) { this.lastName = lastName; } } From snippet above we can see that Person class imposes couple of restrictions on its properties: all of them should not be null. Additionally, email property should contain a valid e-mail address (which will be validated by Hibernate Validator-specific constraint @Email). Pretty simple. Now, let us take a look on JAX-RS 2.0 resources with validation constraints. The skeleton of the PeopleRestService class is bind to /people URL path and is shown below. package com.example.rs;import java.util.Collection;import javax.inject.Inject; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo;import org.hibernate.validator.constraints.Length;import com.example.model.Person; import com.example.services.PeopleService;@Path( "/people" ) public class PeopleRestService { @Inject private PeopleService peopleService;// REST methods here } It should look very familiar, nothing new. The first method we are going to add and decorate with validation constraints is getPerson, which will look up a person by its e-mail address. @Produces( { MediaType.APPLICATION_JSON } ) @Path( "/{email}" ) @GET public @Valid Person getPerson( @Length( min = 5, max = 255 ) @PathParam( "email" ) final String email ) { return peopleService.getByEmail( email ); } There are a couple of differences from traditional JAX-RS 2.0 method declaration. Firstly, we would like the e-mail address (email path parameter) to be at least 5 characters long (but no more than 255 characters) which is imposed by @Length( min = 5, max = 255 ) annotation. Secondly, we would like to ensure that only valid person is returned by this method so we annotated the method’s return value with @Valid annotation. The effect of @Valid is very interesting: the person’s instance in question will be checked against all validation constraints declared by its class (Person). At the moment, Bean Validation 1.1 is not active by default in your Apache CXF projects so if you run your application and call this REST endpoint, all validation constraints will be simply ignored. The good news are that it is very easy to activate Bean Validation 1.1 as it requires only three components to be added to your usual configuration (please check out this feature documentation for more details and advanced configuration):JAXRSBeanValidationInInterceptor in-inteceptor: performs validation of the input parameters of JAX-RS 2.0 resource methods JAXRSBeanValidationOutInterceptor out-inteceptor: performs validation of return values of JAX-RS 2.0 resource methods ValidationExceptionMapper exception mapper: maps the validation violations to HTTP status codes. As per specification, all input parameters validation violations result into 400 Bad Request error. Respectively, all return values validation violations result into 500 Internal Server Error error. At the moment, the ValidationExceptionMapper does not include additional information into response (as it may violate application protocol) but it could be easily extended to provide more details about validation errors.The AppConfig class shows off one of the ways to wire up all the required components together using RuntimeDelegate and JAXRSServerFactoryBean (the XML-based configuration is also supported). package com.example.config;import java.util.Arrays;import javax.ws.rs.ext.RuntimeDelegate;import org.apache.cxf.bus.spring.SpringBus; import org.apache.cxf.endpoint.Server; import org.apache.cxf.interceptor.Interceptor; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor; import org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor; import org.apache.cxf.jaxrs.validation.ValidationExceptionMapper; import org.apache.cxf.message.Message; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn;import com.example.rs.JaxRsApiApplication; import com.example.rs.PeopleRestService; import com.example.services.PeopleService; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;@Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); }@Bean @DependsOn( "cxf" ) public Server jaxRsServer() { final JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) ); factory.setAddress( factory.getAddress() ); factory.setInInterceptors( Arrays.< Interceptor< ? extends Message > >asList( new JAXRSBeanValidationInInterceptor() ) ); factory.setOutInterceptors( Arrays.< Interceptor< ? extends Message > >asList( new JAXRSBeanValidationOutInterceptor() ) ); factory.setProviders( Arrays.asList( new ValidationExceptionMapper(), new JacksonJsonProvider() ) );return factory.create(); }@Bean public JaxRsApiApplication jaxRsApiApplication() { return new JaxRsApiApplication(); }@Bean public PeopleRestService peopleRestService() { return new PeopleRestService(); }@Bean public PeopleService peopleService() { return new PeopleService(); } } All in/out interceptors and exception mapper are injected. Great, let us build the project and run the server to validate the Bean Validation 1.1 is active and works as expected. mvn clean package java -jar target/jaxrs-2.0-validation-0.0.1-SNAPSHOT.jar Now, if we issue a REST request with short (or invalid) e-mail address a@b, the server should return 400 Bad Request. Let us validate that. > curl http://localhost:8080/rest/api/people/a@b -iHTTP/1.1 400 Bad Request Date: Wed, 26 Mar 2014 00:11:59 GMT Content-Length: 0 Server: Jetty(9.1.z-SNAPSHOT) Excellent! To be completely sure, we can check server console output and find there the validation exception of type ConstraintViolationException and its stacktrace. Plus, the last line provides the details what went wrong: PeopleRestService.getPerson.arg0: length must be between 5 and 255 (please notice, because argument names are not currently available on JVM after compilation, they are replaced by placeholders like arg0, arg1, …). WARNING: Interceptor for {http://rs.example.com/}PeopleRestService has thrown exception, unwinding now javax.validation.ConstraintViolationException at org.apache.cxf.validation.BeanValidationProvider.validateParameters(BeanValidationProvider.java:119) at org.apache.cxf.validation.BeanValidationInInterceptor.handleValidation(BeanValidationInInterceptor.java:59) at org.apache.cxf.validation.AbstractValidationInterceptor.handleMessage(AbstractValidationInterceptor.java:73) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307) at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240) at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:197) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:149) at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:167) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:286) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:211) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:262) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:711) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:552) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1112) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:479) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1046) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.Server.handle(Server.java:462) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:281) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:232) at org.eclipse.jetty.io.AbstractConnection$1.run(AbstractConnection.java:505) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:607) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:536) at java.lang.Thread.run(Unknown Source)Mar 25, 2014 8:11:59 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.getPerson.arg0: length must be between 5 and 255 Moving on, we are going to add two more REST methods to demonstrate the collections and Response validation in action. @Produces( { MediaType.APPLICATION_JSON } ) @GET public @Valid Collection< Person > getPeople( @Min( 1 ) @QueryParam( "count" ) @DefaultValue( "1" ) final int count ) { return peopleService.getPeople( count ); } The @Valid annotation on collection of objects will ensure that every single object in collection is valid. The count parameter is also constrained to have the minimum value 1 by @Min( 1 ) annotation (the @DefaultValue is taken into account if the query parameter is not specified). Let us on purpose add the person without first and last names set so the resulting collection will contain at least one person instance which should not pass the validation process. > curl http://localhost:8080/rest/api/people -X POST -id "email=a@b3.com" With that, the call of getPeople REST method should return 500 Internal Server Error. Let us check that is the case. > curl -i http://localhost:8080/rest/api/people?count=10HTTP/1.1 500 Server Error Date: Wed, 26 Mar 2014 01:28:58 GMT Content-Length: 0 Server: Jetty(9.1.z-SNAPSHOT) Looking into server console output, the hint what is wrong is right there. Mar 25, 2014 9:28:58 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.getPeople.[0].firstName: may not be null Mar 25, 2014 9:28:58 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.getPeople.[0].lastName: may not be null And finally, yet another example, this time with generic Response object. @Valid @Produces( { MediaType.APPLICATION_JSON } ) @POST public Response addPerson( @Context final UriInfo uriInfo, @NotNull @Length( min = 5, max = 255 ) @FormParam( "email" ) final String email, @FormParam( "firstName" ) final String firstName, @FormParam( "lastName" ) final String lastName ) { final Person person = peopleService.addPerson( email, firstName, lastName ); return Response.created( uriInfo.getRequestUriBuilder().path( email ).build() ) .entity( person ).build(); } The last example is a bit tricky: the Response class is part of JAX-RS 2.0 API and has no validation constraints defined. As such, imposing any validation rules on the instance of this class will not trigger any violations. But Apache CXF tries its best and performs a simple but useful trick: instead of Response instance, the response’s entity will be validated instead. We can easy verify that by trying to create a person without first and last names set: the expected result should be 500 Internal Server Error. > curl http://localhost:8080/rest/api/people -X POST -id "email=a@b3.com"HTTP/1.1 500 Server Error Date: Wed, 26 Mar 2014 01:13:06 GMT Content-Length: 0 Server: Jetty(9.1.z-SNAPSHOT) And server console output is more verbose: Mar 25, 2014 9:13:06 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.addPerson.<return value>.firstName: may not be null Mar 25, 2014 9:13:06 PM org.apache.cxf.jaxrs.validation.ValidationExceptionMapper toResponse WARNING: PeopleRestService.addPerson.<return value>.lastName: may not be null Nice! In this blog post we have just touched a bit the a topic of how Bean Validation 1.1 may make your Apache CXF projects better by providing such a rich and extensible declarative validation support. Definitely give it a try!A complete project is available on GitHub.Reference: Apache CXF 3.0: JAX-RS 2.0 and Bean Validation 1.1 finally together from our JCG partner Andrey Redko at the Andriy Redko {devmind} blog....

Slim Down SWT FormLayout Usage

Always on the quest for efficiency I reconsidered the usability of SWT FormLayout lately. Although it is one of my favored core layouts with respect to flexibility, I had to recognize that it is only reluctantly used by most of my fellow workers. Proposing it for an appropriate task sometimes actually seems to inflict real physical pain, considering the facial reactions… Indeed, upon closer examination one have to admit that the usage is at least a bit cumbersome. Not so much the layout itself as the FormData configuration for each control under its reach. The following snippet shows a simple use case that – well, I will not spoil the enjoyment of finding out by yourself what it does:   Label label = new Label( composite, SWT.NONE ); FormData labelData = new FormData(); label.setLayoutData( labelData ); labelData.top = new FormAttachment( 0 ); labelData.right = new FormAttachment( 100 ); labelData.bottom = new FormAttachment( 100 ); labelData.left = new FormAttachment( 0 ); Of course everyone is able to figure out the functionality of the code. But it really has the notion of actually figuring it out – and I guess this is part of the problem. So how about programming this less verbose but nevertheless more expressive in the following way: Label label = new Label( composite, SWT.NONE ); attach( label ).atTop().atRight().atBottom().atLeft(); While it is definitely more compact, expressiveness is, at least to some extend, in the eye of the beholder and depends strongly on the metaphor one have of the task at hand. In my imagination FormLayout basically attachs the control boundaries at certain reference points, i.e. the top side atTop, meaning it always keeps the top side of the control at the upper bound of the parent’s client area. Or it attachs a control atTopTo another control, meaning the control’s upper side is always aligned to the bottom of the other control. Furthermore a side can be attached to a percentage range from the respective client area bound, which all could be expressed like this: attach( control ).atLeftTo( otherControl ).fromTop( 20 ); With this mindset I developed a little utility class I called FormDatas to put the outlined ideas into practice. The class provides a static method attach to create a new instance of FormData, which is registered at the control given as parameter. The layout data instance is returned wrapped by a FormDatas object to enable the fluent interfaces style of the configuration methods1. Additionally there are overloaded method variants to handle e.g. the notion of margin or alignment. The margin is based on the underlying Attachment#offset attribute, but actually respects the side of the attachment. Therefore a margin of 5 atRight corresponds to the offset of -5 of an Attachment that has been assigned to the FormData#right attribute with a numerator of 100: attach( label ).atRight( 5 ); is short for FormData formData = new FormData(); label.setLayoutData( formData ); formData.right = new FormAttachment( 100, -5 ); Alignment is backed by the Attachment#alignment attribute and uses the corresponding SWT constants. To adjust a control’s top attachment to the center of another control for example use the following code: attach( control ).atTopTo( otherControl, MARGIN, SWT.CENTER ); And here is yet another scenario that shows how to work with a width hint instead of opposing side attachments: attach( control ).atTop().atRight().atBottom().withWidth( WIDTH ); It is important to mention that the FormDatas implementation does not cover all possibilities of FormData and FormAttachment. But as I was able to replace all use cases in a current project, I hopefully managed to meet the more common ones. From the IDE point of view the best way to integrate the FormDatas is to configure it as favorite. This way the FormDatas.attach(Control) method is available via content assist that automatically handles static imports and the like.If you want to have a look at FormDatas by yourself there is a GitHub gist containing the implementation. However keep in mind that I did not spent any time on documentation, parameter verification or the like. In this regard the utility is a pretty rough cut version that might evolve over time. https://gist.github.com/fappel/9867945 The gist contains the FormDatas and a JUnit test case, as the implementation is meant to be used in production environment and therfore should be tested.FormDatas#attach(Control) is basically a factory method. Because of this it might look a bit strange returning actually an instance of FormDatas. However introducing a new type just for the sake of the fluent interfaces style also seemed a bit odd to me – so if you have a better idea… ↩Reference: Slim Down SWT FormLayout Usage from our JCG partner Frank Appel at the Code Affine blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books