Featured FREE Whitepapers

What's New Here?

software-development-2-logo

A Framework for Enterprise Software

For decades, the companies in this industry have produced sophisticated and complex products. They are difficult to assemble, require the stitching together of a variety of component parts, and its often a long time from the beginning of a project to when the end user sees value/success. Unfortunately, many times, the user is never satisfied. The product breaks or does not work quite as it was described it would. As these quality problems emerge, the companies in this industry turn to 3rd parties, asking the 3rd parties to help their clients have a better experience. The companies incorporate IP from those third parties and many times, they ask the 3rd parties to service the products. While this often improves the customer experience, it does not solve the problem of the negative externalities (and the implications on the users) of the product. In many cases, the negative externalities drive up costs for the users. Then, along comes the threat of a new approach and technology. It simplifies many of the previous issues. The product looks better on the surface and clients tend to be happier, sooner. It also solves the problem of the negative externalities. It’s a homerun all around. Does everyone move to the new approach/technology en masse? Well, you tell me: do you own a battery-powered car? ————————————- The story above is merely an illustration that history repeats itself and there is a lot to be learned from understanding and spotting patterns. I suppose most people who read this will think of enterprise software, as they read that story. And, when I get to the part about the new approach/technology, they start thinking of SaaS and Cloud. However, the answer to the question is the same, whether we are talking autos or enterprise software: The world does not move en masse in any direction, even though benefits are apparent. I continue to see rhetoric that postulates that the future of enterprise software is simply cloud and SaaS. While its hard to argue this at a conceptual level (given its lack of specificity), I think it trivializes a very complex topic. Not everything will be cloud/SaaS, although those will certainly be two possible delivery models. To really form a view of how enterprise software evolves over the next 10-20 years, I’ve constructed some over-arching hypotheses, which hopefully provides a framework for thinking about new business opportunities in enterprise software. Hypothesis 1: The current model of ‘pushing’ your product through a salesforce does not scale and is not optimal for clients/users. Usability will dominate, and I extend usability to include topics like time-to-value, ease of use, and self-service. Hypothesis 2: The model of paying Systems Integrators to make your products work together (or work in the first place) will enter a secular decline. There will continue to be a strong consulting market for application development, high-end strategy/segmentation, and complex project management. However, clients will no longer tolerate having to pay money just to make things work. Hypothesis 3: Enterprises cannot acquire skills fast enough to exploit new technology. So, on one hand, usability needs to address this. On the other hand, continuing education will need to offer a new method for driving skills development quickly. Continuing education is much more than ‘product training’. In fact, while ‘product training’ is the majority that is paid for today…I believe it will be the minority going forward. Hypothesis 4: There will be different models for software delivery: Cloud, SaaS, On-premise, Outsourced, etc. Therefore, just because a company offers something in a certain model does not mean that they will be successful. Clients will buy the best fit model, based on their business goal and related concerns (security, sustainability, etc). Hypothesis 5: Clients will optimize easy (implementation and ongoing support) and return (on investment and capital). Products that deliver on both are a no-brainer. Products that only hit one of them will be scrutinized. Products that deliver neither, will cease to exist. As I meet with new companies and even assess products that we are building, this is my current framework for thinking through how to identify the potential winners and losers.   Reference: A Framework for Enterprise Software from our JCG partner Rob Thomas at the Rob’s Blog blog. ...
java-logo

Is there a better approach to Marker?

Since the launch of Java 1.5 there has been a wide range of discussion and debate on whether to use the Marker interface in Java. This is because Java 1.5 has introduced Annotations features which will pretty much solve the purpose of the Marker interface. This article will cover an interesting section of this debate.Definition:Marker Interface in Java is an empty interface without any methods, fields or constants. This is sometimes also referred as tag interface.  So why Marker interface is used? Valid question!! It doesn’t solve the purpose of the interface which defines a contract with the classes which implement this interface. The interfaces defines methods without their implementation as it tells the child classes what needs to be done but it leaves the decision on the child classes on how to implement this method. However in case of Marker interface there are no members. Marker interface is a way to declare the metadata about a class. It tells the JVM that the objects of the classes which implement the marker interface needs to be treated with special care in a different manner. Some of the out of box Marker interfaces are defined in the Java API are: java.io.Serializable java.lang.Cloneable java.util.RandomAccess java.util.EventListener We can also create our own version of marker interfaces in the same way as we create other interfaces. Let’s go in more depth with the Cloneable interface. When the object needs to be cloned in Java we use the Object’s clone() method. However note that this method is not a part of Cloneable interface i.e. when your class implement the Cloneable interface by default the clone method will not be implemented unlike any other standard interfaces. It can be done when we explicitly define it or call the object’s clone method. Therefore it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed. public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } One key point here is that when you try to clone an object using the clone() method you will get CloneNotSupportedException unless you implement the Cloneable interface. JVM is very smart – isn’t it? Points to note: As mentioned earlier apart from using the built in marker interfaces we can also create application specific marker interfaces as it is a good way of tagging and logically classify your piece of code. This is mainly useful when trying to create a framework or developing API. Interesting points: Runnable is not a Marker interface. Though run is a special instruction to the JVM to start a method but Runnable is not a marker interface because it has a public void run() method inside it. Problem with the marker interface: A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot un-implement a marker. If you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException. Now let’s come back to the point. Is it a better approach to use Annotations than Marker interface? To answer this let’s look into Java Annotations in more details.Definition:Java annotations are special form of syntactic meta-data (data about data) which was introduced in Java 1.5. Like Java Classes, Interfaces even Annotations can be used on several Java elements.Unlike the Javadocs Annotations are more feature rich which helps in processing at runtime. Annotations are used in Package or Class declaration, method declaration, field declaration and variable declaration. It reduces coding effort and let’s developers concentrate on the business logic with the ease of development and hence increases automation. Annotations are demarcated from the standard Java elements by “@” symbol. Whenever the compiler comes across these annotations with any of the Java elements it extracts the information from the annotation and generates the code automatically. Uses of Annotations:Passing information to the compiler – used to detect errors or suppress warnings. E.g. @SuppressWarnings, @deprecated Compiler time and deployment time processing – Several tools can process annotation information to generate code XML file etc. Frameworks like Spring, Hibernate make heavy use of annotations. Run time processing – These annotations are processed only during the runtime.In similar way of Marker interfaces we also have marker annotations. A marker annotation does not have any methods or elements. The behaviour is same as the Marker interfaces. e.g. @Override is a built in Java Marker annotation type that can be implemented to a method to indicate the compiler the compiler that the method overrides a method in a superclass. It does not contain any other program element. If you use this annotation on a method that does not override a superclass method, the compiler issues a compilation error to alert you to this fact. This annotation type guards the programmer against making a mistake when overriding a method as it is quite possible that the developers might actually overload a method in the super class rather than overriding. It seems annotation is a better choice than the marker interface as the same effect can be achieved by the annotations.It can mark variables, methods, and/or classes. It can mark any class specifically, or via inheritance. A marker interface will mark all subclasses of the marked class. E.g. if we have to mark a class non serializable then we have to specifically mark it is as transient. It might be a debatable one as annotations not are not sub classable might be either an advantage or a disadvantage. Annotations are not inherited by default – isAnnotationPresent() tells you if the annotation is present on that particular class, but not if it’s present on a superclass or superinterface. So if you, as the implementer of whatever special functionality the annotation is intended to confer, want the annotation to behave as if it’s inherited – you have to check isAnnotationPresent() on not just this class, but every superclass, and every superinterface. You can add data to the mark. In other words, an annotation that is not blank has value — in that you are marking with more than just type.So each one of them having certain advantage and disadvantage I personally feel that the decision on whether to use marker interface or marker annotation should to be left with the developers as they have to decide considering the situation on the ground and judge on the advantages and disadvantages of both of them and decide on what suits the requirement the best.   Reference: Is there a better approach to Marker? from our JCG partner Mainak Goswami at the Idiotechie blog. ...
java-logo

Java features applicability

Java language and standard library is powerful, but with great power comes great responsibility. After seeing a lot of user code misusing or abusing rare Java features on one hand and completely forgetting about most basic feature on the other, I decided to compose this summary. This is not a list of requirements and areas every Java developer should explore, know and use. It’s quite the opposite! I group Java features in three categories: day to day, occasionally and never (frameworks and libraries only). The rule is simple: if you find yourself using given feature more often then suggested, you are probably over-engineering or trying to build something too general and too reusable. If you don’t use given feature often enough (according to my subjective list), you’re probably missing some really interesting and important opportunities.Note that I only focus on Java, JVM and JDK. I do not suggest which frameworks and how likely you should use. Also I assume typical, server-side business-facing application. Day to day The following features of the Java language are suppose to be used every day. If you have never seen some of them or find yourself using them very rarely, you might take a closer look, they are really helpful:classes, interfaces, packages – seriously. Put your code in classes. You remember from the university that class is an encapsulated data + methods acting upon that data? Class with only state is barely a structure. Class with only methods is just a namespace enclosing functions. Also use interfaces whenever needed. But think twice before creating an interface with only one implementation. Maybe you don’t need a middleman? Nevertheless, put everything in packages, following well established naming convention. static methods – don’t be afraid of them. But use them only for stateless utility methods. Don’t encode any business logic inside static method, ever. ExecutorService – thread pools – creating and effectively using thread pools, understanding how queueing and Future<T> works is a must. Don’t reimplement thread pools, think about them every time someone says producer-consumer. Atomic-* family – don’t use synchronized to barely read/update some counter or reference atomically. Atomic-* family of classes use effective compare-and-swap low-level instructions to be amazingly efficient. Make sure you understand the guarantees these classes provide. design patterns – Not technically a Java language part, but essential. You should, know, understand, and use them willingly but sparingly. Just like with interfaces – don’t go overboard. GoF or even EI patterns should often occur in the code base. But let patterns emerge during your thought process, rather than you letting your thought process be driven by patterns. built-in collections, including concurrent – you absolutely must know and use built in collections, understanding the differences between List, Map and Set. Using thread-safe collections should not be an issue for you. Understand performance characteristics and have basic overview of the implementation behind them. This is really basic. Also know and use various BlockingQueue implementations. Concurrency is hard, don’t make it even harder by reimplementing some of this stuff yourself. Built-in annotations – annotations are here to stay, learn to use @Override (and @Deprecated to some degree) every day consistently. exceptions – use unchecked exceptions to signal abnormal, exceptional failure that requires action being taken. Learn to live with checked exceptions. Learn to read stack traces. try-with-resources – familiarize yourself with this fabulous language construct. Implement AutoCloseable if your class requires any cleanup. Blocking IO – using Reader/Writer, InputStream/OutputStream classes is something you should be really familiar with. Understand the difference between them, using buffering and other decorators without fear.This ends the list of everyday tools you should use. If you’ve never heard of some of them or used them only occasionally, study them more carefully as they might become your lifesavers. Occasionally Following are the language features you should not be afraid to use, but they should not be abused as well. If you find yourself exploiting them every day, if these are kind of features you see several times before lunch, there may be something wrong with your design. I am looking from a back-end, enterprise Java developer perspective. These types of features are useful, but not too often.inheritance and abstract classes – really, it turns out I don’t use inheritance that often and I don’t really miss it. Polymorphism driven by interfaces is by far more flexible, especially with a painful lack of traits in Java. Also prefer composition over inheritance. Too many levels of inheritance lead to very unmaintainable code.regular expressions – Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.. The world without regular expressions would be much more boring and cumbersome. They are wonderful for parsing regular languages (but not HTML) but its way too easy to overuse them. If you find yourself crafting, testing, fixing and coursing whole day in front of regular expressions, you are probably using wrong tool for the job. My all time favourite: public static boolean isNegative(int x) { return Integer.toString(x).matches('-[0-9]+'); }Semaphore, CountDownLatch, CyclicBarrier and others – they are all extremely useful better by an order of magnitude than infomous wait()/notify() pair. But even them won’t prevent you from concurrency bugs when abused. Consider thread-safe collections or some frameworks when you see these synchronization mechanism too often. generic types in user code- using built-in collections and other classes that have generic types should not only be a day to day practice, it should be obvious for you. But I mean developing code yourself taking or returning generic types. Something like this: public <T, F> ContractValidator<T extends Contract> T validate(Validator<T>, F object) It is sometimes necessary to use generics in your own code, but don’t go too meta-. Of course static typing and type safety should be your priority, but maybe you can avoid too many generic, complex types? Scripting languges in JVM – do you know JDK has a built-in JavaScript interpreter? And that you can plug virtually any other language like Groovy or JRuby? Sometimes it’s simpler to embed small script inside your application that can be changed even by the customer. It’s not often, but in very fast changing markets redeploying might not be an option. Just remember that if the total number of lines of scripted code exceeds 1% of the total amount of your code, you should start worrying about maintenance. Java NIO – it is hard to get it right and even harder to actually benefit from it. But in rare cases you actually have to use NIO to squeeze as much performance and scalability as you can. However prefer libraries that can do it for you. Also in normal circumstances blocking IO is typically enough. synchronized keyword – you should not use it too often for a simple reason. The more often it’s used, the more often it’s executed, thus impacting performance. Consider thread-safe collections and atomic primitive wrappers instead. Also make sure you always understand which object is used as a mutex.I consider features above valuable and important, but not necessarily on a day-to-day basis. If you see any of them every single day it might be a sign of over-engineered design or… inexperienced developer. Simplicity comes with experience. However, you might also have very unusual requirements, which applies to the third group as well. Never (think: framework and library developers only) You should know and understand the principles behind the features below in order to understand frameworks and libraries. And you must understand them to effectively us them, I see way too many questions on StackOverflow that could have been avoided if the person in question simply read the code of a library in use. But understanding doesn’t mean use. You should almost never use them directly, they are mostly advanced, dirty and complicated. Even one occurrence of such feature can lead to major headaches.sockets – seriously, sockets. You must understand how TCP/IP stack works, be very conscious with regards to threading, careful when interpreting the data, vigilant with streams. Stay away from using pure sockets, there are hundreds of libraries wrapping them and providing higher level abstractions – HTTP, FTP, NTP, SMB, e-mail… (e.g. see Apache Commons net). You’ll be amazed how hard it is to write decent HTTP client or server. And if you need to write a server for some proprietary protocol, definitely consider Netty. reflection – there is no place for introspecting classes and methods in business code. Frameworks can’t live without reflection, I can’t live with. Reflection makes your code slower, unsafe and ugly. Typically AOP is just enough. I would even say that passing instances of Class<T> around is a code smell. dynamic proxies and byte code manipulation – Proxy class is great, but just like reflection, should be used only by the frameworks and libraries that support you. They are a basic building block of lightweight AOP. If your business application (not framework or library, even Mockito uses these techniques!) requires byte code generation or manipulation (e.g. ASM or CGLIB) -you’re in a deep sh**t I will pray for you. class loaders – everything that has anything to do with class loaders. You must understand them, the hierarchy, bytecode, etc. But if you write your own class loaders, it’s a road to hell. Not that it’s so complicated, but it’s probably unnecessary. Leave it to application servers. Object.html#clone() – honestly, I don’t remember if I ever used that method in my entire (Java developer’s) life. I just… didn’t… And I can’t find any rationale behind using it. I either have an explicit copy constructor or better use immutable objects. Do you have any legitimate use cases for it? It seems so 1990s… native methods – there are a few in JDK, even for such small tasks like computing sine function. But Java is no longer the slowest kid in the class, it’s actually quite the opposite. Also I can’t imagine what kind of logic you need that can’t be achieved using standard library or 3rd-party libraries. Finally, native methods are quite hard to get right, and you can expect low-level, nasty errors, especially around memory management. custom collections – implementing brand new collection following all contracts defined in original JavaDoc is surprisingly hard. Frameworks like Hibernate use special persistent collections. Very rarely you need a collection so specific to your requirements that none of the built-in ones are good enough. ThreadLocal – Libraries and frameworks use thread locals quite often. But you should never try to exploit them for two unrelated reasons. First of all, ThreadLocal is often a hidden semi-global parameter you want to sneak-in. This makes your code harder to reason about and test. Secondly, ThreadLocals can easily introduce memory leaks when not cleaned up properly (see this, this, this and this and…) WeakReference and SoftReference – these classes are quite low-level and are great when implementing caches playing well with garbage collection. Luckily there are plenty of open-source caching libraries, so you don’t have to write one yourself. Understand what these classes do, but don’t use them. com.sun.* and sun.* packages, especially sun.misc.Unsafe – stay away from these packages, just… don’t go there. There is no reason to explore these proprietary, undocumented and not guaranteed to preserve backward compatibility classes. Just pretend they’re not there. And why would you use Unsafe?Of course the list above is completely subjective and most likely not definitive. I encourage you to comment and suggest, if you feel some items are in wrong place or maybe something is missing entirely. I would like to build a summary that can be given as a reference during code review or when a project is evaluated.   Reference: Java features applicability from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog. ...
java-logo

Java Coding Conventions considered harmful

There is an official Code Conventions for the Java Programming Language guide published on Oracle site. You would expect this 20+ pages document to be the most complete, comprehensive and authoritative source of good practices, hints and tips with regards to the Java language. But once you start to read it, disappointment followed by frustration and anger increases. I would like to point out the most obvious mistakes, bad practices, poor and outdated advices given in this guide. In case you are a Java beginner, just forget about this tutorial and look for better and more up-to-date reference materials. Let the horror begin!2.2 Common File Names:GNUmakefile The preferred name for makefiles. We use gnumake to build our software.  gnumake to build Java projects? ant is considered old-school, so is maven. Who uses maketo build WARs, JARs, generate JavaDocs…?3.1.1 Beginning Comments: All source files should begin with a c-style comment that lists the class name, version information, date, and copyright notice: Putting a class name in the comment starting a file? What if I change my mind and rename the class later? And what should that ‘ date‘ represent? Some people use various placeholders to insert last modification time of a file automatically by version control system. Well, VCS is there to tell you when the file was created or last modified – and modifying the same line over and over again makes merging a huge pain.4 – Indentation: Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).Probably the most counterintuitive part of the document. Some prefer spaces, others (including me) – tabs. A matter of taste and team arrangements. But this guide suggests to use both and replace spaces with tabs, sometimes. It’s ‘ unspecified‘. My advice: use tabs and let each developer configure his IDE to have as big or as small indentations as desired. 4.1 Line Length: Avoid lines longer than 80 characters, since they’re not handled well by many terminals and tools. 80 characters? My laptop can easily fit three times as much. Strive for 120-140 characters in one line, but don’t use hard-wraps. Personally I just display vertical margin and the right line length is dictated by readability. BTW here are few examples of classes from various libraries and frameworks:SQLIntegrityConstraintViolationException (JDK 7, 40 characters) AbstractInterruptibleBatchPreparedStatementSetter (Spring framework, 50 characters) AbstractDataSourceBasedMultiTenantConnectionProviderImpl (Hibernate, 56 characters) PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails (Spring Security, 58 characters)And we are suppose to fit whole line in 80 characters? 5.1.2 Single-Line Comments: if (condition) {/* Handle the condition. */ ... } Just in case the code is not self-descriptive enough, I suggest even better comment: if (condition) {/* This block is executed if condition == true. */ ... } 5.1.3 Trailing Comments: if (a == 2) { return TRUE; /* special case */ } else { return isPrime(a); /* works only for odd a */ } Did you mean (and don’t tell me it’s less readable, even without comments)? return a == 2 || isPrime(a); 6.1 Number Per Line: int level; // indentation level int size; // size of table Why use descriptive variable names, when we have comments! Consider this instead: int indentationLevel; int tableSize; Later in that section: In absolutely no case should variables and functions be declared on the same line. Example: long dbaddr, getDbaddr(); // WRONG! Sure it’s wrong, it doesn’t even compile. I’m surprised that ‘ don’t put spaces in variable names ‘ is not mentioned as a good practice… 6.3 Placement: Put declarations only at the beginning of blocks. […] Don’t wait to declare variables until their first use; it can confuse the unwary programmer […] This is how the coding conventions want you to write your code: int min; //inclusive int max; //exclusive int distance; List<String> list; //one per each itemmin = findMin(); max = findMax(); distance = max - min; list = new ArrayList<>(distance); //... And this is how it should be written to avoid confusion: final int minInclusive = findMin(); final int maxExclusive = findMax(); final int distance = maxExclusive - minInclusive; final List<String> listOfItems = new ArrayList<>(distance); //... Besides we can finally ( nomen est omen) use final keyword. Later in this section code sample is shown with class fields missing private modifier (default, package private access). Package private field? 7.3 return Statements: return (size ? size : defaultSize); Maybe you haven’t noticed, but from the context we can tell that both size and defaultSize are of boolean type. That’s right, size and defaultSize can be either true or false (!) How counterintuitive is that! From such a document I would expect not only syntactical correctness, but also meaningful code and good practices! Moreover, the expression can be greatly simplified, step-by-step: size ? size : defaultSize size ? true : defaultSize size || defaultSize 7.5 for Statements: An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form: for (initialization; condition; update);‘ empty for statement‘? Why would you ever use an empty for statement? This is confusing and should be avoided, not encouraged and described in the official language guide. Bonus quiz: what’s the purpose of this code in C? while(*dst++ = *src++); I believe every computer programmer should understand the code snippet above. Even if you program in Ruby or TSQL. 7.8 switch Statements: Every time a case falls through (doesn’t include a break statement), add a comment where thebreak statement would normally be.I understand the intentions, but the approach is wrong. Instead of documenting unexpected and error-prone code-fragments, just avoid them. Don’t depend on fall through, don’t use it at all. 8.1 Blank Lines: One blank line should always be used in the following circumstances: […]Between the local variables in a method and its first statement Before a block […] or single-line […] comment Between logical sections inside a method to improve readabilityLooks like the authors suggest using blank lines to separate  ‘logical sections of a method‘. Well, I call these sections: ‘ methods‘. Don’t group statements inside methods in blocks, comment them and separate from each other. Instead extract them into separate, well named methods! Placing a blank line between variable declarations and the first statement sounds like taken from a C language book. 8.2 Blank Spaces:All binary operators except . should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (‘++‘), and decrement (‘--‘) from their operands. Example:[…] while (d++ = s++) { n++; } This doesn’t even compile in Java… 9 – Naming Conventions (only in PDF version): char *cp; A good name for a char pointer in Java is cp. Wait, WHAT? char pointer in Java? 10.1 Providing Access to Instance and Class Variables:Don’t make any instance or class variable public without good reason. Really, really good reason! Did I ever used public field? 10.4 Variable Assignments: if (c++ = d++) { // AVOID! (Java disallows) ... } Great advice: please avoid using constructs that do not even compile in Java. This makes our lives so much easier! 10.5.2 Returning Values: if (booleanExpression) { return true; } else { return false; } should instead be written asreturn booleanExpression; Holy cow, I AGREE! Summary It’s not that the official Code Conventions for the Java Programming Language are completely wrong. They are just outdated and obsolete. In the second decade of the XXI century we have better hardware, deeper  understanding of code quality and more modern sources of wisdom. Code Conventions… were last published in 1999, they are heavily inspired by C language, unaware of billions of lines of code yet to be written by millions of developers. Code conventions should emerge over time, just like design patterns, rather than be given explicitly. So please, don’t quote or follow advices from official guide ever again. Reference: Java Coding Conventions considered harmful from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog....
whitesource-logo

Open Source Legal Blues: Do You Comply?

Understanding and Reducing Open Source License Risks In today’s business climate, using Open Source Software (OSS) components as part of the development of new products is imperative.  At the same time, the risks of using OSS improperly are enormous. OSS usage introduces legal, business and technical risks. Legally, failure to comply with OSS licensing requirements may result in penalties and other costs. In some cases, companies may even be forced to remove their software from the market. From a business perspective, due diligence processes for M&A and investments require a thorough audit of all OSS components, and deals have been aborted due to tainted IP and expensive licensing obligations. In addition, some resellers and even enterprise customers have started to enforce OSS policies, and to demand transparency from software vendors. From a technical perspective, OSS security vulnerabilities may call for intruders who can review the publicly available code searching for holes. Thus, it is important to maintain good visibility into your OSS usage, and to make informed decisions in real time. Most companies are addressing OSS challenges using spreadsheets and other static documents. This leads to missing and out of date information, lack of collaboration, and no clear way to evaluate risk. Some commercial tools are available but require companies to exert substantial effort to track and validate OSS. With these tools, much of the compliance work is done near major and high risk events such as M&A, OEM deals, and new version releases. White Source, the leading SaaS Open Source Lifecycle Management platform, introduces a new approach. White Source provides a comprehensive, yet affordable, solution for companies that need to manage their open source assets and ensure license compliance. White Source SaaS service is easy to use, requires very little effort from developers and is always up-to-date.With White Source, new open source components are automatically detected when first used, and classified by their license type and risk profile. This allows the organization to immediately address the respective risks and license requirements, rather than wait until release time, thereby risking substantial development effort, and unnecessary delays.White Source integrates seamlessly and can automatically enforce organizational open source policy with leading development tools such as Apache maven, Apache Ant, Jenkins, JetBrains TeamCity, RedHat OpenShift, CloudBees and JFrog Artifactory. White Source is hosting a free webinar on November 13th, 10am EST titled “Open Source Legal Blues: Do You Comply?” The webinar will feature renowned IP legal expert Haim Ravia, and White Source CEO Rami Sass.The session will cover:Open source legal, business, and technical risks. How to effectively manage the open source adoption process, review procedures, and compliance requirements. How to do so without impacting development and release schedules, and without spending a small fortune.Register Now  ...
spring-interview-questions-answers

Spring Constructor Injection and Argument names

At runtime, java classes do not retain the name of the constructor or method parameters, unless classes are compiled with debug options on.This has some interesting implications for Spring Constructor Injection.Consider the following simple class    package dbg; public class Person {private final String first; private final String last; private final Address address;public Person(String first, String last, Address address){ this.first = first; this.last = last; this.address = address; }public String getFirst() { return first; }public String getLast() { return last; }public Address getAddress() { return address; } }and a sample Spring bean configuration xml file:<bean name='address1' class='dbg.Address' p:street1='street1' p:street2='street1' p:state='state1'/> <bean name='person1' class='dbg.Person' c:address-ref='address1' c:last='Last1' c:first='First1' ></bean> <bean name='person2' class='dbg.Person' c:first='First2' c:address-ref='address1' c:last='Last2' ></bean>Here I am using the c namespace for constructor injection. This fails with the exception that the argument types are ambiguous – this is because the first argument is a String and since its runtime representation does not have the argument name present, Spring cannot determine if it should be substituted for the first name or last. There are a couple of fixes possible for this scenario: 1. To use index based constructor injection, the drawback though is that it is very verbose:<bean name='person1' class='dbg.Person' > <constructor-arg value='First1'></constructor-arg> <constructor-arg value='Last1'></constructor-arg> <constructor-arg ref='address1'></constructor-arg> </bean> <bean name='person2' class='dbg.Person' > <constructor-arg value='First2'></constructor-arg> <constructor-arg value='Last2'></constructor-arg> <constructor-arg ref='address1'></constructor-arg> </bean>2. To compile with debug symbols on, this can be done by passing a -g or -g:var flag to the java compiler – this will ensure that the parameter names are preserved in the class file and the original concise bean configuration with c namespace will work. 3. A neat fix is to annotate the constructor with @ConstructorProperties which basically provides the argument names to Spring:public class Person {private final String first; private final String last; private final Address address;@ConstructorProperties({'first','last','address'}) public Person(String first, String last, Address address){ this.first = first; this.last = last; this.address = address; }This works with or without debug options turned on. 4. Probably the best fix of all is to simply use @Configuration to define the beans:@Configuration public static class TestConfiguration{@Bean public Address address1(){ return new Address(); } @Bean public Person person1(){ return new Person('First1', 'Last1', address1()); } @Bean public Person person2(){ return new Person('First2', 'Last2', address1()); }} Reference: Spring Constructor Injection and Argument names from our JCG partner Biju Kunjummen at the all and sundry blog. ...
groovy-logo

Grails: Autodiscovery of JPA-annotated domain classes

There are some issues to be fixed with the support for adding JPA annotations (for example @Entity) to Groovy classes in grails-app/domain in 2.0. This is due to the changes made to adding most GORM methods to the domain class bytecode with AST transformations instead of adding them to the metaclass at runtime with metaprogramming. There is a workaround – put the classes in src/groovy (or write them in Java and put them in src/java). This adds a maintenance headache though because by being in grails-app/domain the classes are automatically discovered, but there’s no scanning of src/groovy or src/java for annotated classes so they must be explicitly listed in grails-app/conf/hibernate/hibernate.cfg.xml. We do support something similar with the ability to annotate Groovy and Java classes with Spring bean annotations like @Component and there is an optional property grails.spring.bean.packages in Config.groovy that can contain one or more packages names to search. We configure a Spring scanner that looks for annotated classes and automatically registers them as beans. So that’s what we need for JPA-annotated src/groovy and src/java classes. It turns out that there is a Spring class that does this, org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean. It extends the standard SessionFactory factory bean class org.springframework.orm.hibernate3.LocalSessionFactoryBean and adds support for an explicit list of class names to use and also a list of packages to scan. Unfortunately the Grails factory bean class org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean also extends LocalSessionFactoryBean so if you configure your application to use AnnotationSessionFactoryBean you’ll lose a lot of important functionality from ConfigurableLocalSessionFactoryBean. So here’s a subclass of ConfigurableLocalSessionFactoryBean that borrows the useful annotation support from AnnotationSessionFactoryBean and can be used in a Grails application: package com.burtbeckwith.grails.jpa;import java.io.IOException;import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.persistence.MappedSuperclass;import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean; import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration; import org.hibernate.HibernateException; import org.hibernate.MappingException; import org.hibernate.cfg.Configuration; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternUtils; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.util.ClassUtils;/** * Based on org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean. * @author Burt Beckwith */ public class AnnotationConfigurableLocalSessionFactoryBean extends ConfigurableLocalSessionFactoryBean implements ResourceLoaderAware {private static final String RESOURCE_PATTERN = '/**/*.class';private Class<?>[] annotatedClasses; private String[] annotatedPackages; private String[] packagesToScan;private TypeFilter[] entityTypeFilters = new TypeFilter[] { new AnnotationTypeFilter(Entity.class, false), new AnnotationTypeFilter(Embeddable.class, false), new AnnotationTypeFilter(MappedSuperclass.class, false), new AnnotationTypeFilter(org.hibernate.annotations.Entity.class, false)};private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();public AnnotationConfigurableLocalSessionFactoryBean() { setConfigurationClass(GrailsAnnotationConfiguration.class); }public void setAnnotatedClasses(Class<?>[] annotatedClasses) { this.annotatedClasses = annotatedClasses; }public void setAnnotatedPackages(String[] annotatedPackages) { this.annotatedPackages = annotatedPackages; }public void setPackagesToScan(String[] packagesToScan) { this.packagesToScan = packagesToScan; }public void setEntityTypeFilters(TypeFilter[] entityTypeFilters) { this.entityTypeFilters = entityTypeFilters; }public void setResourceLoader(ResourceLoader resourceLoader) { this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); }@Override protected void postProcessMappings(Configuration config) throws HibernateException { GrailsAnnotationConfiguration annConfig = (GrailsAnnotationConfiguration)config; if (annotatedClasses != null) { for (Class<?> annotatedClass : annotatedClasses) { annConfig.addAnnotatedClass(annotatedClass); } } if (annotatedPackages != null) { for (String annotatedPackage : annotatedPackages) { annConfig.addPackage(annotatedPackage); } } scanPackages(annConfig); }protected void scanPackages(GrailsAnnotationConfiguration config) { if (packagesToScan == null) { return; }try { for (String pkg : packagesToScan) { logger.debug('Scanning package '' + pkg + '''); String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN; Resource[] resources = resourcePatternResolver.getResources(pattern); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); if (matchesFilter(reader, readerFactory)) { config.addAnnotatedClass(resourcePatternResolver.getClassLoader().loadClass(className)); logger.debug('Adding annotated class '' + className + '''); } } } } } catch (IOException ex) { throw new MappingException('Failed to scan classpath for unlisted classes', ex); } catch (ClassNotFoundException ex) { throw new MappingException('Failed to load annotated classes from classpath', ex); } }private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { if (entityTypeFilters != null) { for (TypeFilter filter : entityTypeFilters) { if (filter.match(reader, readerFactory)) { return true; } } } return false; } } You can replace the Grails SessionFactory bean in your application’s grails-app/conf/spring/resources.groovy by using the same name as the one Grails registers: import com.burtbeckwith.grails.jpa.AnnotationConfigurableLocalSessionFactoryBeanbeans = { sessionFactory(AnnotationConfigurableLocalSessionFactoryBean) { bean -> bean.parent = 'abstractSessionFactoryBeanConfig' packagesToScan = ['com.mycompany.myapp.entity'] } } Here I’ve listed one package name in the packagesToScan property but you can list as many as you want. You can also explicitly list classes with the annotatedClasses property. Note that this is for the “default” DataSource; if you’re using multiple datasources you will need to do this for each one. So this means we can define this class in src/groovy/com/mycompany/myapp/entity/Person.groovy: package com.mycompany.myapp.entityimport javax.persistence.Column import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.Id import javax.persistence.Version@Entity class Person {@Id @GeneratedValue Long id@Version @Column(nullable=false) Long version@Column(name='first', nullable=false) String firstName@Column(name='last', nullable=false) String lastName@Column(nullable=true) String initial@Column(nullable=false, unique=true, length=200) String email } It will be detected as a domain class and if you run the schema-export script the table DDL will be there in target/ddl.sql. There are a few issues to be aware of however, mostly around constraints. You can’t define a constraints or mapping block in the class – they will be ignored. The mappings that you would have added just need to go in the annotations. For example I have overridden the default names for the firstName and lastName properties in the example above. But nullable=true is the default for JPA and it’s the opposite in Grails – properties are required by default. So while the annotations will affect the database schema, Grails doesn’t use the constraints from the annotations and you will get a validation error for this class if you fail to provide a value for the initial property. You can address this by creating a constraints file in src/java; see the docs for more details. So in this case I would create src/java/com/mycompany/myapp/entity/PersonConstraints.groovy with a non-static constraints property, e.g. constraints = { initial(nullable: true) email unique: true, length: 200) } This way the Grails constraints and the database constraints are in sync; without this I would be able to create an instance of the domain class that has an email with more than 200 characters and it would validate, but cause a database constraint exception when inserting the row. This also has the benefit of letting you use the Grails constraints that don’t correspond to a JPA constraint such as email and blank.   Reference: Autodiscovery of JPA-annotated domain classes in Grails from our JCG partner Burt Beckwith at the An Army of Solipsists blog. ...
java-logo

Github Gists in Eclipse

I’d like to describe simple steps regarding integrating GitHub Gists in Eclipse. There are several sources which provoke me to do this:GitHub Mylyn connector for Eclipse EGit/GitHub/User Guide http://eclipse.github.comI’ve been using Eclipse Java EE destibution, Mylyn plugin has been already installed there:1. Install EGit plugin via Eclipse Marketplace:2. Install GitHub Mylyn Connector via Eclipse Marketplace:3. Open View ‘Task List’ and click ‘Add Repository':4. Add Mylyn Task repository – ‘GitHub Gists':5 .Then you should create Mylyn Query to fetch all Gists:6. You should get something like this:That’s it. PS. Please note I’ve excluded such common sense steps as providing credentials for your GitHub account.   Reference: Github Gists in Eclipse from our JCG partner Orest Ivasiv at the Knowledge Is Everything blog. ...
zk-logo

Advanced ZK: Asynchronous UI updates and background processing – part 2

Introduction In part 1 I showed how server push and threads can be used to execute background tasks in a ZK application. However, the simple example had a major flaw that makes it a bad approach for real-world applications: it starts a new thread for each background task. JDK5 introduced the ExecutorService class, which abstracts away the threading details, and gives us a nice interface which can be used to submit tasks for background processing. In this blog post I will describe the most important parts of creating a ZK app, which contains a background task that takes a string, and returns it in uppercase. The complete sample project is available at Github: https://github.com/Gekkio/blog/tree/master/2012/10/async-zk-part-2 1. Create an ExecutorService instance First we need an ExecutorService that we can use in our ZK code. In most cases we want a shared singleton instance, which could be configured and managed by dependency injection (e.g. Spring). It is very important to make sure that the ExecutorService is created only once, and it’s shut down properly with the application. In this sample project I will use a simple holder class, which manages the lifecycle of a single statically available ExecutorService instance. This holder must be configured as a listener in zk.xml. package sample;import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;import org.zkoss.zk.ui.WebApp; import org.zkoss.zk.ui.util.WebAppCleanup; import org.zkoss.zk.ui.util.WebAppInit;public class SampleExecutorHolder implements WebAppInit, WebAppCleanup {private static volatile ExecutorService executor;public static ExecutorService getExecutor() { return executor; }@Override public void cleanup(WebApp wapp) throws Exception { if (executor != null) { executor.shutdown(); System.out.println('ExecutorService shut down'); } }@Override public void init(WebApp wapp) throws Exception { executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); System.out.println('Initialized an ExecutorService'); }} Note that the thread pool is configured using a fixed size based on processors in the system. Proper thread pool sizing is very important, and depends on the type of tasks you intend to execute. The maximum number of threads is also the maximum amount of simultaneous concurrent tasks! 2. Write event classes that model the results of the background task We’ll use ZK server push to communicate the task results back to the UI, so the results must be modeled as ZK events. It’s always a good idea to create custom subclasses of Event instead of adding the results in the data parameter, because a custom class is more typesafe and can supports multiple fields. The first event class represents a status update that is sent while the task is still running. In this example it will contain the amount of characters in the input string. package sample;import org.zkoss.zk.ui.event.Event;public class FirstStepEvent extends Event {public final int amountOfCharacters;public FirstStepEvent(int amountOfCharacters) { super('onFirstStepCompleted', null); this.amountOfCharacters = amountOfCharacters; }} The second event class represents the fully completed task. In this example it contains the input string in upper case. package sample;import org.zkoss.zk.ui.event.Event;public class SecondStepEvent extends Event {public final String upperCaseResult;public SecondStepEvent(String upperCaseResult) { super('onSecondStepCompleted', null); this.upperCaseResult = upperCaseResult; }}   3. Write the task class The task class should have the following characteristics:It implements Runnable It takes all required input data as constructor arguments (the data should be immutable if possible!). This input data must be thread-safe, and generally should not include any ZK-related stuff (no components, sessions, etc.). For example, if you want to use a Textbox value as input, read the value in advance and don’t pass the Textbox itself as an argument. It takes a Desktop, and at least one EventListener as constructor arguments. They are needed for sending the results back to the UIIn this example the only input data is a string that will be used to compute the task results. package sample;import java.util.Locale;import org.zkoss.zk.ui.Desktop; import org.zkoss.zk.ui.DesktopUnavailableException; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener;public class SampleTask implements Runnable {private final String input; private final Desktop desktop; private final EventListener<Event> eventListener;@SuppressWarnings({ 'rawtypes', 'unchecked' }) public SampleTask(String input, Desktop desktop, EventListener eventListener) { this.input = input; this.desktop = desktop; this.eventListener = eventListener; }@Override public void run() { try { // Step 1 Thread.sleep(10000); Executions.schedule(desktop, eventListener, new FirstStepEvent(input.length()));// Step 2 Thread.sleep(10000); Executions.schedule(desktop, eventListener, new SecondStepEvent(input.toUpperCase(Locale.ENGLISH))); } catch (DesktopUnavailableException e) { System.err.println('Desktop is no longer available: ' + desktop); } catch (InterruptedException e) { } }} Note how all the constructor arguments are stored in private final fields, and how the input data is immutable (Strings are immutable in Java!). The task simulates long-running processing by using Thread.sleep, and submits a status event when the “processing” is half done. 4. Schedule tasks in ZK composers Using the task in composers is very simple. You only need to enable server push, and submit a new task instance to the executor. This automatically starts the task once a free background thread is available. desktop.enableServerPush(true); // Get the executor from somewhere executor = SampleExecutorHolder.getExecutor(); executor.execute(new SampleTask(input.getValue(), desktop, this)); In this sample the composer extends GenericForwardComposer, which implements EventListener, so it can itself handle the resulting task events. Both events are handled by methods that update the UI with status information. public void onFirstStepCompleted(FirstStepEvent event) { status.setValue('Task running: ' + event.amountOfCharacters + ' characters in input'); }public void onSecondStepCompleted(SecondStepEvent event) { status.setValue('Task finished: ' + event.upperCaseResult); }   Final words It’s quite easy to add robust support for long-running tasks in a ZK application by using this technique. The resulting code in ZK composers is very simple, because the results are passed using the typical Event/EventListener paradigm that is very common within ZK apps. The biggest dangers in this technique are thread-safety bugs, which can be very difficult to debug. It is absolutely crucial to fully understand the threads where every piece of code is executed, and ensure that all shared state is fully thread-safe. Using immutable input data, and immutable output events is usually enough to ensure safety as long as the background task itself doesn’t access other non-thread-safe resources. Some common mistakes are:Invoking thread-local dependent library methods in the background task (e.g. any method that seems to magically get the “current” value of some type). The background threads will not automatically contain the same thread-local values as servlet threads, so by default all these kind of methods will fail. For example Sessions.getCurrent(), Executions.getCurrent() in ZK, many Spring Security static methods. Passing non-thread-safe parameters to the background task. For example, passing a mutable List that might be modified by the composer while the task is running (always make copies of mutable collections!). Passing non-thread-safe result data in events. For example, passing a List in a result event, while the List will be modified later on in the task (always make copies of mutable collections!). Accessing non-thread-safe methods in the desktop. Even though you have access to the desktop in the background task, most desktop methods are not thread-safe. For example, calling desktop.isAlive() is not guaranteed to return the status correctly (at least in ZK 6.5 the method relies on non-volatile fields, so writes are not guaranteed to be visible in the background thread)  Reference: Advanced ZK: Asynchronous UI updates and background processing – part 2 from our JCG partner Joonas Javanainen at the Jawsy Solutions technical blog blog. ...
java-interview-questions-answers

Rest using Jersey – Complete Tutorial with JAXB, Exception Handling and Client Program

Recently I started working on a Restful web service project using Jersey API. There are some tutorials available online but I faced some issues with exception handling and I didn’t found anywhere complete project using JaxB and providing exception handling approach. So once I was able to create a Restful web service using Jersey API with exception handling and client program, I decided to write this tutorial to help everyone getting started with Jersey. Who Should Use This Tutorial This tutorial is intended for Java programmers who are interested in developing and deploying Restful Web Services using Jersey API and JaxB. Prerequisites The scope of this tutorial is to use Jersey API for creating Restful web services and invoking the web service using Java client program and testing web service using tool. Basic understanding of Java, Web Services, XML, Maven and any application server (JBoss/Tomcat) is required to understand the tutorial with ease. Softwares and Tools usedJDK version 1.6.0_37 Apache Maven 3.0.3 Mac OS X 10.8.2 JBoss 4.2.2 (You can use any application server like Tomcat, Glassfish etc.) Eclipse Indigo (Any Java IDE with Maven support)Creating Maven Project in Eclipse and Jersey Create a maven project in Eclipse and it will provide you with basic project structure. I have given GroupId as “JD” and artifactID as “my-jersey-project” but you can give anything you like. Once we complete the development of our project, it will look like below in the image.  Jersey Web service project explanation pom.xml: Project configuration details, note the jersey dependencies provided, other details are common for any maven project. <project xmlns='http://maven.apache.org/POM/4.0.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'> <modelVersion>4.0.0</modelVersion> <groupId>JD</groupId> <artifactId>my-jersey-project</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging><dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.14</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-servlet</artifactId> <version>1.14</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.14</version> </dependency> </dependencies><build> <finalName>${artifactId}-${version}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.1-alpha-2</version> <configuration> <packagingExcludes> WEB-INF/lib/servlet-api-*.jar </packagingExcludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.0</version> <executions> <execution> <id>unpack</id> <phase>install</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>${groupId}</groupId> <artifactId>${artifactId}</artifactId> <version>${version}</version> <type>${packaging}</type> <overWrite>true</overWrite> <outputDirectory>${project.build.directory}/${artifactId}-${version}-exploded.${packaging}</outputDirectory> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> EmpRequest.java: Java Bean for the request object. The important thing to note here is @XmlRootElement annotation to map the class to an XML element. package com.jd.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = 'empRequest') public class EmpRequest { private int id; private String name;public int getId() { return id; }public void setId(int id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; } } EmpResponse.java: Java bean for the response object. package com.jd.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = 'empResponse') public class EmpResponse { private int id; private String name;public int getId() { return id; }public void setId(int id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; }} ErrorResponse.java: Java Bean that will be send as response incase of exception. package com.jd.model;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = 'errorResponse') public class ErrorResponse {private String errorCode; private int errorId;public String getErrorCode() { return errorCode; }public void setErrorCode(String errorCode) { this.errorCode = errorCode; }public int getErrorId() { return errorId; }public void setErrorId(int errorId) { this.errorId = errorId; }} EmpNotFoundException.java: A normal exception class thrown in the web service. package com.jd.exception;public class EmpNotFoundException extends Exception {private static final long serialVersionUID = 4351720088030656859L; private int errorId;public int getErrorId() { return errorId; }public EmpNotFoundException(String msg, int errorId) { super(msg); this.errorId = errorId; }public EmpNotFoundException(String msg, Throwable cause) { super(msg, cause); } } jboss-web.xml: To define JBoss servlet context for the web service. <jboss-web> <context-root>jd</context-root> </jboss-web> web.xml: Deployment descriptor for the web service. So any request with URI “http://<HOST>:<POST>/jd/rest/*” will be processed by Jersey ServletContainer servlet. Important thing to note is the init-param value passed for “com.sun.jersey.config.property.packages”. This defines in which package jersey will look for the web service classes. This property must point to your resources classes. It also looks for the resource classes into the sub-packages. <?xml version='1.0' encoding='UTF-8'?> <web-app id='WebApp_ID' version='2.5' xmlns='http://java.sun.com/xml/ns/javaee' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd'><display-name>My Jersey Project</display-name><!-- Jersey Servlet configurations --> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.jd</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <!-- Jersey Servlet configurations --></web-app> EmpRouter.java: Resource class handling different kinds of request.@Path(“/emp”) – All the requests with URI http://<HOST>:<PORT>/jd/rest/emp/ will be processed by this resource class. @Path(“/getEmp”) – All the requests with URI http://<HOST>:<PORT>/jd/rest/emp/getEmp will be processed by this method. @POST – This annotation defines that the HTTP method used should be POST. Some other possible values are @GET, @PUT, @DELETE @Consumes(MediaType.APPLICATION_XML) – The method accepts XML element @Produces(MediaType.APPLICATION_XML) – The method returns XML elementpackage com.jd.router;import com.jd.exception.EmpNotFoundException; import com.jd.model.*;import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.JAXBElement;@Path('/emp') public class EmpRouter {@POST @Path('/getEmp') @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response getEmp(JAXBElement<EmpRequest> empRequest) throws EmpNotFoundException { EmpResponse empResponse = new EmpResponse(); if (empRequest.getValue().getId() == 1) { empResponse.setId(empRequest.getValue().getId()); empResponse.setName(empRequest.getValue().getName()); } else { throw new EmpNotFoundException('Wrong ID', empRequest.getValue() .getId()); } return Response.ok(empResponse).build(); } } EmpNotFoundExceptionMapper.java: Exception Mapper class that maps EmpNotFoundException to Response object. The class should have annotation @Provider. This class should be in the package provided for resource classes in web.xml. Implementation of toResponse() method generates the ErrorResponse object and set it as Entity in Response object with status as INTERNAL_SERVER_ERROR. package com.jd.exceptionmapper;import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider;import com.jd.exception.EmpNotFoundException; import com.jd.model.ErrorResponse;@Provider public class EmpNotFoundExceptionMapper implements ExceptionMapper<EmpNotFoundException> {public EmpNotFoundExceptionMapper() { }public Response toResponse( EmpNotFoundException empNotFoundException) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setErrorId(empNotFoundException.getErrorId()); errorResponse.setErrorCode(empNotFoundException.getMessage()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( errorResponse).type( MediaType.APPLICATION_XML).build();}} Our web service is ready, just build it to create the WAR file and deploy it in the application server. EmpClient.java: This is a sample java program through which are invoking our web service. We are using jersey client API to invoke the service and based on response status we are parsing response entity to EmpResponse or ErrorResponse class. package com.jd.client;import javax.ws.rs.core.MediaType;import com.jd.model.EmpRequest; import com.jd.model.EmpResponse; import com.jd.model.ErrorResponse; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource;public class EmpClient {/** * @param args */ public static void main(String[] args) { String uri = 'http://localhost:8080/jd/rest/emp/getEmp'; EmpRequest request = new EmpRequest(); //set id as 1 for OK response request.setId(2); request.setName('PK'); try{ Client client = Client.create(); WebResource r=client.resource(uri); ClientResponse response = r.type(MediaType.APPLICATION_XML).post(ClientResponse.class,request ); System.out.println(response.getStatus()); if(response.getStatus() == 200){ EmpResponse empResponse = response.getEntity(EmpResponse.class); System.out.println(empResponse.getId() + '::'+empResponse.getName()); }else{ ErrorResponse exc = response.getEntity(ErrorResponse.class); System.out.println(exc.getErrorCode()); System.out.println(exc.getErrorId()); } }catch(Exception e){ System.out.println(e.getMessage()); } }} I hope the tutorial is easy enough to follow and write your first Restful web service using Jersey. Please let me know if you face any issues or need further explanations.   Reference: Rest using Jersey – Complete Tutorial with JAXB, Exception Handling and Client Program from our JCG partner Pankaj Kumar at the Developer Recipes blog. ...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close