Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

and many more ....

Featured FREE Whitepapers

What's New Here?

spring-data-logo

Customizing Spring Data JPA Repository

Spring Data is a very convenient library. However, as the project as quite new, it is not well featured. By default, Spring Data JPA will provide implementation of the DAO based on SimpleJpaRepository. In recent project, I have developed a customize repository base class so that I could add more features on it. You could add vendor specific features to this repository base class as you like. Configuration You have to add the following configuration to you spring beans configuration file. You have to specified a new repository factory class. We will develop the class later. <jpa:repositories base-package='example.borislam.dao' factory-class='example.borislam.data.springData.DefaultRepositoryFactoryBean/> Just develop an interface extending JpaRepository. You should remember to annotate it with @NoRepositoryBean. @NoRepositoryBean public interface GenericRepository <T, ID extends Serializable> extends JpaRepository<T, ID> { }Define Custom repository base implementation class Next step is to develop the customized base repository class. You can see that I just one property (i.e. springDataRepositoryInterface) inside this customized base repository. I just want to get more control on the behaviour of the customized behaviour of the repository interface. I will show how to add more features of this base repository class in the next post. @SuppressWarnings('unchecked') @NoRepositoryBean public class GenericRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements GenericRepository<T, ID> , Serializable{ private static final long serialVersionUID = 1L;static Logger logger = Logger.getLogger(GenericRepositoryImpl.class); private final JpaEntityInformation<T, ?> entityInformation; private final EntityManager em; private final DefaultPersistenceProvider provider; private Class<?> springDataRepositoryInterface; public Class<?> getSpringDataRepositoryInterface() { return springDataRepositoryInterface; }public void setSpringDataRepositoryInterface( Class<?> springDataRepositoryInterface) { this.springDataRepositoryInterface = springDataRepositoryInterface; }/** * Creates a new {@link SimpleJpaRepository} to manage objects of the given * {@link JpaEntityInformation}. * * @param entityInformation * @param entityManager */ public GenericRepositoryImpl (JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager , Class<?> springDataRepositoryInterface) { super(entityInformation, entityManager); this.entityInformation = entityInformation; this.em = entityManager; this.provider = DefaultPersistenceProvider.fromEntityManager(entityManager); this.springDataRepositoryInterface = springDataRepositoryInterface; }/** * Creates a new {@link SimpleJpaRepository} to manage objects of the given * domain type. * * @param domainClass * @param em */ public GenericRepositoryImpl(Class<T> domainClass, EntityManager em) { this(JpaEntityInformationSupport.getMetadata(domainClass, em), em, null); } public <S extends T> S save(S entity) { if (this.entityInformation.isNew(entity)) { this.em.persist(entity); flush(); return entity; } entity = this.em.merge(entity); flush(); return entity; } public T saveWithoutFlush(T entity) { return super.save(entity); } public List<T> saveWithoutFlush(Iterable<? extends T> entities) { List<T> result = new ArrayList<T>(); if (entities == null) { return result; }for (T entity : entities) { result.add(saveWithoutFlush(entity)); } return result; } }As a simple example here, I just override the default save method of the SimpleJPARepository. The default behaviour of the save method will not flush after persist. I modified to make it flush after persist. On the other hand, I add another method called saveWithoutFlush() to allow developer to call save the entity without flush. Define Custom repository factory bean The last step is to create a factory bean class and factory class to produce repository based on your customized base repository class. public class DefaultRepositoryFactoryBean <T extends JpaRepository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> { /** * Returns a {@link RepositoryFactorySupport}. * * @param entityManager * @return */ protected RepositoryFactorySupport createRepositoryFactory( EntityManager entityManager) {return new DefaultRepositoryFactory(entityManager); } }/** * * The purpose of this class is to override the default behaviour of the spring JpaRepositoryFactory class. * It will produce a GenericRepositoryImpl object instead of SimpleJpaRepository. * */ public class DefaultRepositoryFactory extends JpaRepositoryFactory{ private final EntityManager entityManager; private final QueryExtractor extractor;public DefaultRepositoryFactory(EntityManager entityManager) { super(entityManager); Assert.notNull(entityManager); this.entityManager = entityManager; this.extractor = DefaultPersistenceProvider.fromEntityManager(entityManager); } @SuppressWarnings({ 'unchecked', 'rawtypes' }) protected <T, ID extends Serializable> JpaRepository<?, ?> getTargetRepository( RepositoryMetadata metadata, EntityManager entityManager) {Class<?> repositoryInterface = metadata.getRepositoryInterface(); JpaEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());if (isQueryDslExecutor(repositoryInterface)) { return new QueryDslJpaRepository(entityInformation, entityManager); } else { return new GenericRepositoryImpl(entityInformation, entityManager, repositoryInterface); //custom implementation } } @Override protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {if (isQueryDslExecutor(metadata.getRepositoryInterface())) { return QueryDslJpaRepository.class; } else { return GenericRepositoryImpl.class; } } /** * Returns whether the given repository interface requires a QueryDsl * specific implementation to be chosen. * * @param repositoryInterface * @return */ private boolean isQueryDslExecutor(Class<?> repositoryInterface) {return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class .isAssignableFrom(repositoryInterface); } }Conclusion You could now add more features to base repository class. In your program, you could now create your own repository interface extending GenericRepository instead of JpaRepository. public interface MyRepository <T, ID extends Serializable> extends GenericRepository <T, ID> { void someCustomMethod(ID id); } In next post, I will show you how to add hibernate filter features to this GenericRepository. Reference: Customizing Spring Data JPA Repository from our JCG partner Boris Lam at the Programming Peacefully blog....
software-development-2-logo

5′ on IT-Architecture: the modern software architect

Before I start writing about this let me adjust something right at the beginning: Yes of course, there is the role of a ‘software architect’ in any non-trivial software development project. Even in times of agile projects, dynamic markets and vague terms like ‘emergence’. The simple reason for that is that emergence and democracy in teams only work within constraints. Though, it’s not always clever to assign somebody the role explicitly. In an ideal world one developer in that team evolves into the architecture role. When I started working as an IT professional at a *big* american software & IT consulting company I spent around five years with programming. After that time I got my first architecture job on a big project at a german automotive manufacturer. My main responsibility was to design the solution, advice developers, project managers and clients in doing things and to organize the development process. I wrote many documents, but I didn’t code anymore. The result was that I lost expertise in my core business: programming. So after a while my assessments and gut instinct got worse, which results in worse decisions. As a sideeffect of generic (vague) talking it got harder to gain acceptance by the developers, project managers or clients. When I realized all that I decided to do more development again. Today, I am doing architecture for 10 years. I am developing code in the IDE of my choice at least 20-30% of my time. Avtivity profile Whilst programming is a necessary activity, there is a whole bunch of activities that are sufficient to be successful as an architect. Doing architecture is a lot about collaboration, evaluating alternatives objectively (neutral and fair-minded) and about decision making. It’s a lot about communication, dealing with other individuals that almost always have their own opinions. Further more it’s a lot about forming teams and designing the ideal development process around those teams to solve the concrete problem. Last not least it’s about designing (structuring) the solution in a way that all functional and non-functional requirements are well covered. You can do all that more or less without super actual technical knowledge. But I believe an architect can do better if he/she has technical expertise gathered by day-to-day coding business. In the long run you cannot be a technical architect without sufficient coding practice. Figure 1: Activities of the software architectSolving tradeoffs When I worked as an architect I often found myself in difficult tradeoff situations. That is, I wanted to improve one quality attribute, but to achieve that I needed to downgrade another. Here is a simple but very common example: its often desireable to have a highly changeable system with best possible performance. However, these two attributes – performance and changeability – typically correlate negatively, when you want to increase changeability you often loose efficiency. Doing architecture often means to find the golden mean between competing system qualities – it means choosing the right alternative that represents the best compromise. It’s about finding the balance between system qualities and the environmental factors of that system (e.g. steakholders, requirements). The operations manager will focus on the efficiency of a new system, while the development manager will argue that it’s important to have a changeable system that generates little maintenance costs. The client wants to have a new system with the highest degree of business process automation as possible. These situations consume a reasonalbe amount of time and energy. Sharing knowledge and communication Another superior important activity: sharing knowledge in a team of technical experts and other steakholders. The core problem of software development is to transform fuzzy knowledge of domain experts into merciless logical machine code of silly computers that only understand two digits: 0 and 1. This is a long way through the venturesome and endless jungle of human misunderstandings! Therefore, architects communicate a lot. They use models to do that. Models serve as a mapping mechanism between human brains and computers. The set of problems that can arise during the knowledge-to-binary transformation is very diverse. It’s impossible that every team member knows all of them. That’s another reason why sharing knowledge in a team is so superior important. Nobody is perfect! Needless to say that nobody is perfect. Every team is different and so is every concrete situation. So in one situation one may be the right architect for the team while in other team set-ups that person doesn’t fit. An architect can also have different strengths. I know architects that communicate and socialize very well but don’t do so good in designing solutions or organizing the development process. Although they don’t master each individual skill, they’re all good architects. The common ground is that they were all down-to-earth developers. Reference: 5′ on IT-Architecture: the modern software architect from our JCG partner Niklas....
android-logo

Android Activity Animation Customization Tutorial

If you are thinking on customizing the animation of Activity transition then probably you would look for ActivityOptions class introduced in Android 4.1 (Jelly bean). This class has provided three methods which can help you to customize the Activity Animation. These are given in the table below. ActivityOptions Class MethodsFunction Name DescriptionmakeCustomAnimation This method allows to pass custom animation and when the Atyctivi is launched, it gets rendered accordingly. Here you can pass animation for transitioning out Activity as well as for transitioning in ActivitymakeScaleUpAnimation This method scales up the Activity from the initial size to its final representational size. It can be used to scale up the activity from the view which has launched this activity.makeThumbnailScaleUpAnimation In this animation, a thumbnail of the activity scales up to the final size of the activity.toBundle This method returns Bundle object which can be passed in the startActivity() method for desired animation.For more information on ActivityOptions you can refer here. Project Information: Meta-data about the project. Platform Version : Android API Level 16. IDE : Eclipse Helios Service Release 2 Emulator : Android 4.1(API 16) Prerequisite: Preliminary knowledge of Android application framework, and Intent. Sample Source Code: We create a project using eclipse and then create anim (Animation) folder under res(resource) folder. Now we will define the animation attributes in the xml files and put it in anim folder. Here, we are going to define two animations which will be used in makeCustomAnimation() method. makeCustomAnimation takes two animation files, one for incoming activity and another for outgoing activity. Either of the animations can be null and in that case animation will not be performed for that particular activity. Now we will define fade_in.xml for incoming activity. Here we are going to change the Alpha value from 0 to 1 which makes activity transparent to opaque. <alpha xmlns:android='http://schemas.android.com/apk/res/android' android:interpolator='@android:anim/anticipate_interpolator' android:fromAlpha='0.0' android:toAlpha='1.0' android:duration='@android:integer/config_longAnimTime' /> Now we are going to define the another file called fade_out.xml file for transitioning out Activity. Here we will change the value of Alpha from 1 to 0. <alpha xmlns:android='http://schemas.android.com/apk/res/android' android:interpolator='@android:anim/anticipate_interpolator' android:fromAlpha='1.0' android:toAlpha='0.0' android:duration='@android:integer/config_longAnimTime' /> Now we are going to define the layout file for the main activity. Name this file as acitivity_main.xml. In this file we will add three buttons for corresponding animation. <LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' xmlns:tools='http://schemas.android.com/tools' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' ><Button android:layout_width='match_parent' android:layout_height='wrap_content' android:onClick='fadeAnimation' android:text='@string/btFadeAnimation' /> <Button android:layout_width='match_parent' android:layout_height='wrap_content' android:onClick='scaleupAnimation' android:text='@string/btScaleupAni' /> <Button android:layout_width='match_parent' android:layout_height='wrap_content' android:onClick='thumbNailScaleAnimation' android:text='@string/btThumbNailScaleupAni' /></LinearLayout> As you may have noticed that we have already attached onclick method with each button. These methods will animate the activity when it is launched using startActivity() method. Now let’s define the another layout for the target Activity with one ImageView. Put an image in drawable folder and then use that image as src for Image view. Here I have put “freelance2.jpg” image in drawable folder and have used android:src tag to use the image. Name the layout file as activity_animation.xml <RelativeLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' > <ImageView android:id='@+id/imageView1' android:layout_width='match_parent' android:layout_height='match_parent' android:layout_marginRight='44dp' android:layout_marginTop='54dp' android:layout_centerInParent='true' android:src='@drawable/freelancer2' /></RelativeLayout> Once this layout is defined, we need to define the corresponding Activity class. Let’s name this class as AnimationActivity. The source code is as following: package com.example.jellybeananimationexample;import android.app.Activity; import android.os.Bundle;public class AnimationActivity extends Activity {@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_animation); } }Now, it’s time to define the MainActivity class having methods to customize the Activity animation. package com.example.jellybeananimationexample;import android.app.Activity; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View;public class MainActivity extends Activity {@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }public void scaleupAnimation(View view) { // Create a scale-up animation that originates at the button // being pressed. ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight()); // Request the activity be started, using the custom animation options. startActivity(new Intent(MainActivity.this, AnimationActivity.class), opts.toBundle()); }public void thumbNailScaleAnimation(View view) { view.setDrawingCacheEnabled(true); view.setPressed(false); view.refreshDrawableState(); Bitmap bitmap = view.getDrawingCache(); ActivityOptions opts = ActivityOptions.makeThumbnailScaleUpAnimation( view, bitmap, 0, 0); // Request the activity be started, using the custom animation options. startActivity(new Intent(MainActivity.this, AnimationActivity.class), opts.toBundle()); view.setDrawingCacheEnabled(false); }public void fadeAnimation(View view) { ActivityOptions opts = ActivityOptions.makeCustomAnimation( MainActivity.this, R.anim.fade_in, R.anim.fade_out); // Request the activity be started, using the custom animation options. startActivity(new Intent(MainActivity.this, AnimationActivity.class), opts.toBundle()); }} Once you are done with code, execute it. On clicking the application button, you will see the customized activity animation. You can get the updated Android Animation source code from here. For Android tutorial visit here. Reference: Tutorial on customization of Android Activity Animation from our JCG partner Rakesh Cusat at the Code4Reference blog....
gradle-logo

How to install Gradle

Gradle is a simple and yet strong build tool. It is similar to the Ant build tool. It manages the build well and also handles build dependencies. The best part of Gradle is that it is open source project. If you are thinking about installing and giving it a try, then you are at the right place. Gradle development cycle is of 4 weeks, so after every four weeks they roll out a new version of Gradle. Here, I am assuming that you are going to install Gradle on linux/Ubuntu machine. Gradle setup stepsDownload Gradle from here. Gradle download comes in three different flavors.Binaries, Documentation and Source code Binaries only Source code onlyThe first one is recommended since it comes with documentation and source code. If you are not interested in documentation and source file, you can download Binaries only package.   unzip the download file $unzip gradle-[version]-[type].ziphere type can be all, bin, or src. It is based on type of downloaded flavor. The bin file should be in the system path, only then you can execute the Gradle command. It can be done either by executing the command given below or by editing the .bashrc to set the PATH variable. #modify the directory path according to the setup. $ export PATH=$PATH:/gradle-directory-path/gradle-directory/binNow execute the following command on terminal $ gradle #you will see the output below.:helpWelcome to Gradle 1.1.To run a build, run gradle ... To see a list of available tasks, run gradle tasks To see a list of command-line options, run gradle --help BUILD SUCCESSFUL Total time: 2.607 secsIf you don’t the the above print, then you need to recheck the PATH variable.Hello wold!! in Gradle After installing Gradle, let’s try a simple Gradle file. Create a file named build.gradle and copy the code given below in this file. task("hello"){ println "Hello world!!" }The way we define targets in Makefile, similarly we define tasks in gradle script. In the above code we have created a simple task called hello which prints Hello world!!. For executing this script, just execute the command below on the terminal in the same directory. $ gradle hello #you will get similar out put as shown below.Hello world!! :hello UP-TO-DATEBUILD SUCCESSFULGradle command looks for build.gradle file in the current directory and executes the specified task(s) similar to make command which looks for Makefile in the current directory and executes the specified target(s). Reference: how to install gradle from our JCG partner Rakesh Cusat at the Code4Reference blog....
java-logo

Java Enums: You have grace, elegance and power and this is what I Love!

While Java 8 is coming, are you sure you know well the enums that were introduced in Java 5? Java enums are still underestimated, and it’s a pity since they are more useful than you might think, they’re not just for your usual enumerated constants! Java enum is polymorphic Java enums are real classes that can have behavior and even data. Let’s represent the Rock-Paper-Scissors game using an enum with a single method. Here are the unit tests to define the behavior: @Test public void paper_beats_rock() { assertThat(PAPER.beats(ROCK)).isTrue(); assertThat(ROCK.beats(PAPER)).isFalse(); } @Test public void scissors_beats_paper() { assertThat(SCISSORS.beats(PAPER)).isTrue(); assertThat(PAPER.beats(SCISSORS)).isFalse(); } @Test public void rock_beats_scissors() { assertThat(ROCK.beats(SCISSORS)).isTrue(); assertThat(SCISSORS.beats(ROCK)).isFalse(); } And here is the implementation of the enum, that primarily relies on the ordinal integer of each enum constant, such as the item N+1 wins over the item N. This equivalence between the enum constants and the integers is quite handy in many cases. /** Enums have behavior! */ public enum Gesture { ROCK() { // Enums are polymorphic, that's really handy! @Override public boolean beats(Gesture other) { return other == SCISSORS; } }, PAPER, SCISSORS;// we can implement with the integer representation public boolean beats(Gesture other) { return ordinal() - other.ordinal() == 1; } } Notice that there is not a single IF statement anywhere, all the business logic is handled by the integer logic and by the polymorphism, where we override the method for the ROCK case. If the ordering between the items was not cyclic we could implement it just using the natural ordering of the enum, here the polymorphism helps deal with the cycle.You can do it without any IF statement! Yes you can!This Java enum is also a perfect example that you can have your cake (offer a nice object-oriented API with intent-revealing names), and eat it too (implement with simple and efficient integer logic like in the good ol’ days). Over my last projects I’ve used a lot enums as a substitute for classes: they are guaranted to be singleton, have ordering, hashcode, equals and serialization to and from text all built-in, without any clutter in the source code. If you’re looking for Value Objects and if you can represent a part of your domain with a limited set of instances, then the enum is what you need! It’s a bit like the Sealed Case Class in Scala, except it’s totally restricted to a set of instances all defined at compile time. The bounded set of instances at compile-time is a real limitation, but now with continuous delivery, you can probably wait for the next release if you really need one extra case.   Well-suited for the Strategy pattern Let’s move to to a system for the (in-)famous Eurovision song contest; we want to be able to configure the behavior on when to notify (or not) users of any new Eurovision event. It’s important. Let’s do that with an enum: /** The policy on how to notify the user of any Eurovision song contest event */ public enum EurovisionNotification {/** I love Eurovision, don't want to miss it, never! */ ALWAYS() { @Override public boolean mustNotify(String eventCity, String userCity) { return true; } },/** * I only want to know about Eurovision if it takes place in my city, so * that I can take holidays elsewhere at the same time */ ONLY_IF_IN_MY_CITY() { // a case of flyweight pattern since we pass all the extrinsi data as // arguments instead of storing them as member data @Override public boolean mustNotify(String eventCity, String userCity) { return eventCity.equalsIgnoreCase(userCity); } },/** I don't care, I don't want to know */ NEVER() { @Override public boolean mustNotify(String eventCity, String userCity) { return false; } };// no default behavior public abstract boolean mustNotify(String eventCity, String userCity);} And a unit test for the non trivial case ONLY_IF_IN_MY_CITY: @Test public void notify_users_in_Baku_only() { assertThat(ONLY_IF_IN_MY_CITY.mustNotify("Baku", "BAKU")).isTrue(); assertThat(ONLY_IF_IN_MY_CITY.mustNotify("Baku", Paris")).isFalse(); } Here we define the method abstract, only to implement it for each case. An alternative would be to implement a default behavior and only override it for each case when it makes sense, just like in the Rock-Paper-Scissors game. Again we don’t need the switch on enum to choose the behavior, we rely on polymorphism instead. You probably don’t need the switch on enum much, except for dependency reasons. For example when the enum is part of a message sent to the outside world as in Data Transfer Objects (DTO), you do not want any dependency to your internal code in the enum or its signature. For the Eurovision strategy, using TDD we could start with a simple boolean for the cases ALWAYS and NEVER. It would then be promoted into the enum as soon as we introduce the third strategy ONLY_IF_IN_MY_CITY. Promoting primitives is also in the spirit of the 7th rule « Wrap all primitives » from the Object Calisthenics, and an enum is the perfect way to wrap a boolean or an integer with a bounded set of possible values. Because the strategy pattern is often controlled by configuration, the built-in serialization to and from String is also very convenient to store your settings.   Perfect match for the State pattern Just like the Strategy pattern, the Java enum is very well-suited for finite state machines, where by definition the set of possible states is finite.A baby as a finite state machine (picture from www.alongcamebaby.ca)Let’s take the example of a baby simplified as a state machine, and make it an enum: /** * The primary baby states (simplified) */ public enum BabyState {POOP(null), SLEEP(POOP), EAT(SLEEP), CRY(EAT);private final BabyState next;private BabyState(BabyState next) { this.next = next; }public BabyState next(boolean discomfort) { if (discomfort) { return CRY; } return next == null ? EAT : next; } } And of course some unit tests to drive the behavior: @Test public void eat_then_sleep_then_poop_and_repeat() { assertThat(EAT.next(NO_DISCOMFORT)).isEqualTo(SLEEP); assertThat(SLEEP.next(NO_DISCOMFORT)).isEqualTo(POOP); assertThat(POOP.next(NO_DISCOMFORT)).isEqualTo(EAT); }@Test public void if_discomfort_then_cry_then_eat() { assertThat(SLEEP.next(DISCOMFORT)).isEqualTo(CRY); assertThat(CRY.next(NO_DISCOMFORT)).isEqualTo(EAT); } Yes we can reference enum constants between them, with the restriction that only constants defined before can be referenced. Here we have a cycle between the states EAT -> SLEEP -> POOP -> EAT etc. so we need to open the cycle and close it with a workaround at runtime. We indeed have a graph with the CRY state that can be accessed from any state. I’ve already used enums to represent simple trees by categories simply by referencing in each node its elements, all with enum constants.   Enum-optimized collections Enums also have the benefits of coming with their dedicated implementations for Map and Set: EnumMap and EnumSet. These collections have the same interface and behave just like your regular collections, but internally they exploit the integer nature of the enums, as an optimization. In short you have old C-style data structures and idioms (bit masking and the like) hidden behind an elegant interface. This also demonstrate how you don’t have to compromise your API’s for the sake of efficiency! To illustrate the use of these dedicated collections, let’s represent the 7 cards in Jurgen Appelo’s Delegation Poker: public enum AuthorityLevel {/** make decision as the manager */ TELL,/** convince people about decision */ SELL,/** get input from team before decision */ CONSULT,/** make decision together with team */ AGREE,/** influence decision made by the team */ ADVISE,/** ask feedback after decision by team */ INQUIRE,/** no influence, let team work it out */ DELEGATE; There are 7 cards, the first 3 are more control-oriented, the middle card is balanced, and the 3 last cards are more delegation-oriented (I made that interpretation up, please refer to his book for explanations). In the Delegation Poker, every player selects a card for a given situation, and earns as many points as the card value (from 1 to 7), except the players in the « highest minority ». It’s trivial to compute the number of points using the ordinal value + 1. It is also straightforward to select the control oriented cards by their ordinal value, or we can use a Set built from a range like we do below to select the delegation-oriented cards: public int numberOfPoints() { return ordinal() + 1; }// It's ok to use the internal ordinal integer for the implementation public boolean isControlOriented() { return ordinal() < AGREE.ordinal(); }// EnumSet is a Set implementation that benefits from the integer-like // nature of the enums public static Set DELEGATION_LEVELS = EnumSet.range(ADVISE, DELEGATE);// enums are comparable hence the usual benefits public static AuthorityLevel highest(List levels) { return Collections.max(levels); } } EnumSet offers convenient static factory methods like range(from, to), to create a set that includes every enum constant starting between ADVISE and DELEGATE in our example, in the declaration order. To compute the highest minority we start with the highest card, which is nothing but finding the max, something trivial since the enum is always comparable. Whenever we need to use this enum as a key in a Map, we should use the EnumMap, as illustrated in the test below: // Using an EnumMap to represent the votes by authority level @Test public void votes_with_a_clear_majority() { final Map<AuthorityLevel, Integer> votes = new EnumMap(AuthorityLevel.class); votes.put(SELL, 1); votes.put(ADVISE, 3); votes.put(INQUIRE, 2); assertThat(votes.get(ADVISE)).isEqualTo(3); } Java enums are good, eat them! I love Java enums: they’re just perfect for Value Objects in the Domain-Driven Design sense where the set of every possible values is bounded. In a recent project I deliberatly managed to have a majority of value types expressed as enums. You get a lot of awesomeness for free, and especially with almost no technical noise. This helps improve my signal-to-noise ratio between the words from the domain and the technical jargon. Or course I make sure each enum constant is also immutable, and I get the correct equals, hashcode, toString, String or integer serialization, singleton-ness and very efficient collections on them for free, all that with very little code.  (picture from sys-con.com – Jim Barnabee article) »]The power of polymorphismThe enum polymorphism is very handy, and I never use instanceof on enums and I hardly need to switch on the enum either. I’d love that the Java enum is completed by a similar construct just like the case class in Scala, for when the set of possible values cannot be bounded. And a way to enforce immutability of any class would be nice too. Am I asking too much? Also <troll>don’t even try to compare the Java enum with the C# enum…</troll> Reference: Java Enums: You have grace, elegance and power and this is what I Love! from our JCG partner Cyrille Martraire at the Cyrille Martraire’s blog blog....
software-development-2-logo

How to win or fail when writing software: A car analogy

I realized a common analogy would be a useful tool to help non-engineers and non-developers… why not a car? A modern vehicle is a feat of engineering. Rolling down the highway at 70mph means all sorts of vibrations and harmful oscillations must be damped out to prevent the vehicle from destroying itself. Modern vehicles like my truck actually have a LAN-like network called a CAN(Controller Area Network) that connects everything from the transmission to the radio on a single digital bus. A lot of research and development goes into making a vehicle, so how does that compare to software development? Engineering a vehicle has many phases, the early stages being definition, planning, and experimentation; lets focus in on a few of these.DefinitionThe first step of any development process should be definition, or creating a vocabulary for the problem space. The goal is to make sure everyone is talking about the same thing. For instance, in web application development, a user and a customer can be different people!While designing a car, there is driver, passenger, steering wheel, e-brake, and many more. These terms must be used consistently in the development lifecycle. Ambiguities must be sought and destroyed. For instance, is a driver also a passenger? Or perhaps driver and passengers are both occupants? This critical step is glossed over by Agile methodologists that want to jump right into coding.A great (and free) resource on how to create a business vocabulary is Domain Driven Design Quickly, by Eric Evans. Eric steps through the process of creating an air traffic control system. Nearly an entire chapter is spent defining the actors, nouns, actions, and relationships in the air traffic control ecosystem before introducing any DDD concepts.If you’re a non-engineer, you should demand your developers create this vocabulary with you. As you’re painfully aware, communicating what you want with developers is difficult. Creating a vocabulary is a communication channel. Do not skip straight into development or design without it!  PlanningWhen GM had automotive engineers design the Chevy Volt, it’s unlikely they that put a bunch of sticky notes on a board that said, “A user should be able to steer the car in a particular direction,” then ran off willy-nilly and built out the steering rack from modern hydraulic actuators. Later on, in sprint 25, when they got around to building the engine, they realized that a hydraulic steering rack isn’t ideal for an electric car. Turns out, hydraulics require a constant pressure from a turning pump, and an electric vehicle’s motor isn’t turning at red lights.They didn’t spend 8 years drawing on paper either, then started building the car. Each time they designed a component of the vehicle, they had to change the plans for the rest of the vehicle. Their design was iterative and if you look at the early prototypes, they look nothing like the final product.Neither extreme is healthy and unfortunately Agile developers tend to want to get started quickly without thinking of the big picture. Old school waterfall developers like to think that once they develop a plan, they should never ever change it, and also think that they can foresee all the problems that would arise with a particular design.Software engineers should fall somewhere in the middle. After user stories are somewhat complete, a domain model should be developed that shows object attributes and how they relate to the rest of the domain. After the domain design is created, an architecture plan should then be developed that shows how objects stored, processed, and shuffled around the system. Cross cutting concerns, such as logging, monitoring, and auditing should be introduced at this point.Unfortunately, there is not easy road for non-engineers here. Your developers should have a technical plan, and they should be able to explain it to you in a way you understand. Each iteration the technical plan and model should be updated and changed. If your developers actually keep the same technical plan between iterations, this should be a red flag: No one gets it right the first time. During development, your engineers will encounter business scenarios and technical problems the team simply didn’t think of. Each iteration should be a refinement, or even a roadmap change if you really just “got it wrong.”  ExperimentationAs I said earlier, GM didn’t spend 8 years drawing the design out on paper until they thought they solved every possible problem that popped into their heads. After they defined their vocabulary and came up with a basic design, GM experimented with 25 different battery chemistries in real life using various test platforms to validate their design. Turns out, some manufacturers had no idea that their batteries tended to explode.Research and development is something you can actually write off on your taxes. R&D should be done at the beginning of every iteration, after design, before development. Creating, measuring, and analyzing the performance, productivity, and maintainability of a particular design will help you weed out expensive mistakes. Developers should concentrate on creating specific goals, and communicate effectively to their peers what they did, why they did it, and what happened. A wiki is a great place to store R&D results and later, when creating the tax writeoffs, accounting can show that actual R&D was done.This is an area that developers love, and business managers don’t understand. Business managers tend to think playing with shiny development toys is a waste of time when ‘real work’ implementing requirements should be done. (If you work for a company like this, I encourage you to quit your job. These types of factories deserve to be talent starved and are not worth working for)The trick to making sure that real work is done is timeboxing R&D and setting goals. Specific goals should first be defined, then an appropriately sized timebox is allotted proportionately to the experiment. Specific goals might be evaluating one framework over another, or one design over another. Large R&D boxes should be allocated at the beginning of the project, with small ones at the end. Again, the goal here is to avoid waste. Being proactive rather than reactive, while counterintuitive, will only make your project succeed. …there are things that we now know we don’t know. But there are also unknown unknowns. There are things we do not know we don’t know-Donald Rumsfeld (An odd person to say such a quote)The ultimate goal of R&D is to discover the things you don’t know that you don’t know. Discovering failures proactively saves you time and makes developers happy.  ConclusionThe difference between “coding” and “engineering” is that engineering wants to be deterministic and predictable. Coders tend to jump straight into things without giving long-term business goals thought, then jump ship when the waters get rough. The solution is to follow all steps of an engineering lifecycle while producing engineering artifacts such as models and plans. Finally, just like a car, models and plans require maintenance, and should be changed and upgraded frequently during the engineering lifecycle.Reference: How to win or fail when writing software: A car analogy from our JCG partner Jonathan Fisher at the The Code Mechanic blog....
java-logo

Java Annotations: Explored & Explained

One of the many wonderful features of Java 5 SE is the introduction of the Annotations construct. Annotations are tags that we can insert into our program source code for some tool to process it and make sense out of it. Annotations processing tools generally use Reflection API (of Java 5 SE) to process the code at source level on Java code or bytecode level to process the class files into which the compiler has placed the annotations. Java Annotations are wonderfully explained in many places around the web, but the only place where I could find a sensible and complete example was a hard bound book by Prentice Hall Publications named Core Java : Volume II – Advanced Features, authored by Cay S. Horstmann and Gary Cornell. Almost all the places on web that try to explain Annotations miss the most crucial part of showing us an Annotation Processing Tool (APT) for our custom written annotations and the way to use it from our code. I have used the information from the book to build some Annotations for validating variables and initializing values in them from property files for my project. My observation of the lack of examples over the www for writing custom Java Annotations has motivated me to write this article. So, presenting to you a sample custom Java Annotation to help you write your own Annotations for whatever it is you may be doing.           I will take you through the NullValueValidate annotation whose purpose as its name suggests is to validate the variable it annotates to be containing a non null value. If it finds a null value while processing then it will throw a NullPointerException.Declaring an Annotation Lets begin by declaring our annotation. This declaration will be used by the code that intends to use the annotation to annotate the variables in its object. package annotation.declaration; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/** * Null Value Validate is, as the name suggests an annotation to * validate whether the parameter is null or not * @author Y.Kamesh Rao * */ @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME)public @interface NullValueValidate { String paramName(); } Note the ‘@’(AT) symbol in front of the ‘interface’ keyword. This is the syntax used to declare an annotation. This is called an annotation interface. The methods of the interface correspond to the elements of the annotation. paramName() – This is the only element our annotation declaration consists of. It stores the name of the annotated field to display it in a message while processing. Note that the declaration looks like a function declaration. Actually, that is what it is. @interface actually declares a Java interface whose implementation is provided by the objects that use the annotation. Annotation processors receive the objects that use/implement the annotation and they call annotation interface methods to retrieve the annotation elements. In our case, the NullValueValidateAnnotationProcessor would receive the object of the class that has some fields annotated using the NullValueValidate annotation. This processor would then call the paramName() method to retrieve the value of this annotation element. We use 3 of the Java provided Annotations to annotate the properties of our declaration. These are alternatively referred to as the Built-In Annotations and are used for ‘Annotating an Annotation’. (Well, there are much tougher tongue twisters than this). @Documented – Indicates that the annotation declaration has to be included while creating the docs for this project using JavaDocs. By default, Annotations are excluded from the documentation generated using the javadocs command. @Target – Indicates the target elements in your java program to which the annotation shall be applied. It can either the Field, Method, Class or the whole Package itself. Our NullValueValidateannotation shall be applicable to only class fields. Here are the possible values taken by this Enum –TYPE – Applied only to Type. A Type can be a Java class or interface or an Enum or even an Annotation. FIELD – Applied only to Java Fields (Objects, Instance or Static, declared at class level). METHOD – Applied only to methods. PARAMETER – Applied only to method parameters in a method definition. CONSTRUCTOR – Can be applicable only to a constructor of a class. LOCAL_VARIABLE – Can be applicable only to Local variables. (Variables that are declared within a method or a block of code). ANNOTATION_TYPE – Applied only to Annotation Types. PACKAGE – Applicable only to a Package.@Retention - Indicates the retention policy to be used for the annotation. In simple words, for long would we retain the annotation. There are three possible values –SOURCE – Annotations are to be discarded by the compiler. CLASS – Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. This is the default behavior. RUNTIME – Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.We have set the RetentionPolicy to be RUNTIME since we plan to process the annotations at runtime of the program. @Target and @Retention are also called Meta-Annotations.Annotation Processing Tool An annotation processor tool, parses the object it receives and takes programmed actions on finding the annotations it is processing in the object under scrutiny. Here is the annotation processor for our previously declared annotation – NullValueValidate. package annotation.processor;import java.lang.annotation.Annotation; import java.lang.reflect.Field; import annotation.declaration.NullValueValidate;/** * The class file to actually carry out the validations * for the various validate annotations we have declared * @author Y.Kamesh Rao */ public class NullValueValidateAnnotationProcessor { /** * Method to process all the annotations * @param obj The name of the object where * annotations are to be identified and * processed */ public static void processAnnotations(Object obj) { try { Class cl = obj.getClass();// Checking all the fields for annotations for(Field f : cl.getDeclaredFields()) { // Since we are Validating fields, there may be many // NullPointer and similar exceptions thrown, // so we need to catch them try { // Processing all the annotations on a single field for(Annotation a : f.getAnnotations()) { // Checking for a NullValueValidate annotation if(a.annotationType() == NullValueValidate.class) { NullValueValidate nullVal = (NullValueValidate) a; System.out.println('Processing the field : '+ nullVal.paramName());// Setting the field to be accessible from our class // is it is a private member of the class under processing // (which its most likely going to be) // The setAccessible method will not work if you have // Java SecurityManager configured and active. f.setAccessible(true);// Checking the field for a null value and // throwing an exception is a null value encountered. // The get(Object obj) method on Field class returns the // value of the Field for the Object which is under test right now. // In other words, we need to send 'obj' as the object // to this method since we are currently processing the // annotations present on the 'obj' Object. if(f.get(obj) == null) { throw new NullPointerException('The value of the field '+f.toString()+' can't be NULL.'); } else System.out.println('Value of the Object : '+f.get(obj)); } } } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } Most of the code is self explanatory with comments that it has. Please refer the code for detailed understanding of the same. Basically, it has a static method called processAnnotations that takes the object of the class which contains annotations that need to be processed. We then use Java Reflection API to process each of the Field in this received object parameter and take necessary actions of null value validation whenever we find a NullValueValidate Annotation on the field. If a null value is found, we throw the NullPointerException or we print the value on the console. Annotation UsagePlease refer the following code that uses the NullValueValidate annotation that we just implemented. It also uses the NullValueValidateAnnotationProcessorto process the declared annotations on its field at runtime by calling it from its constructor. Also do note that the annotations are used in a similar fashion as access modifiers like private or public with the variable/field declarations. Usually a newline is entered for better readability of the code. Else, the annotation can very well exist in the same line as the variable/field declaration. The name of the annotation is preceded by an ‘@’(AT) symbol. package annotation;import annotation.declaration.NullValueValidate; import annotation.processor.NullValueValidateAnnotationProcessor;/** Main class to test the Annotations * @author Y.Kamesh Rao */ public class AnnotationExample { @NullValueValidate(paramName = 'testVar1') private String testVar1; @NullValueValidate(paramName = 'testVar2') private String testVar2;public AnnotationExample() { testVar2 = 'Testing the Null Value Validation...It Works...!'; // Calling the processor to process the annotations applied // on this class object. NullValueValidateAnnotationProcessor.processAnnotations(this); } public static void main(String args[]) { AnnotationExample ae = new AnnotationExample(); } } Output Processing the field:testVar1 Value of the Object:Testing the Null Value Validation...It Works...! Processing the field:testVar2 The value of the field private java.lang.String annotation.AnnotationExample.testVar2 cannot be NULL. java.lang.NullPointerException:The value of the field private java.lang.String annotation.AnnotationExample.testVar2 cannot be NULL. at annotation.processor.NullValueValidateAnnotationProcessor.processAnnotation (NullValueValidateAnnotationProcessor.java:66) at annotation.AnnotationExample.(AnnotationExample.java:28) at annotation.AnnotationExample.main(AnnotationExample.java:33)Conclusion I had a lot of fun doing this sample annotation program and now I have implemented many custom made Annotations to load properties from property files, validations of database field lengths, etc. Annotations greatly reduces the verbosity of the code thus making it much simpler and readable. Annotations can be used for logging, generating code dependent deployment descriptors and other mechanical and repetitive jobs. I had a lot of fun compiling this article for you guys. I hope you benefit from it. Reference: Java Annotations: Explored & Explained from our JCG partner Y Kamesh Rao at the OrangeApple blog....
jboss-logo

JBoss Core Java Web Services

This blog post deals with Web Services. Well, to be more exact, it deals with ‘plain’ java web services on JBoss. That means we are going to create a web service without any additional frameworks (like CXF, Axis etc.). JBoss it self provides support for web services. So if you are really trying to build basic web service (or if you just wish to learn about web services and try different things), JBoss Web Services should be a good starting point. Here we go! Web Service Let’s first talk about the Web Service it self. What is a Web Service. People have a tendency to say that the web service is no more then a process of remote method invocation (RMI). In reality, it is not just about RMI. Web Service is a collection of endpoints (or a single endpoint) exposed via HTTP protocol. In order to communicate with these endpoints, we have to create clients to access the end points. The biggest advantage of this kind of communication between the web service end point and a client is that is specified by SOAP protocol which builds on top of HTTP protocol (or sometimes even SMTP protocol). This protocol defines the structure of the data which is transferred between the end point and the client. The data is exchanged in XML format. As a consequence, web service are said to be ‘platform/technology’ independent. For example a web service can be implemented by using Java CXF framework or plain JBoss Web Services. The client which access this web service can be implemented in, let’s say, non java environment. Web service technology and a technology of the client can be totally different and communication between them is still possible because the SOAP protocol relies on XML message format. Only thing required of this communication to succeed is that both, the end point and the client, agree how the XML message should look like (what kind of fields and what type of content will exist in the xml file) and what are the operations (methods) which client can invoke on the end point. These requirements are specified by the WSDL. WSDL (Web Services Description Language) is an XML based language which is used to describe the end points of the web service. It can define the HTTP address of the end point, operations which can be executed by the client on this end point, type of the data which can be passed to the operations and what type of data is received back form those operations of the endpoints. It also defines the exact structure of the XML messages which are used in a communication with the endpoint. This kind of information is usually stored in the file with wsdl extension. That is how the famous term ‘wsdl file’ came to the world. Ok, that is enough about web services. Actually, i could write a lot about web services and SOAP protocol, but that would be outside of the scope of this blog. You are encouraged to do so your self. There are plenty of articles in the internet about this subject. Creating a simple Web Service on JBoss Example I am about to show you is in eclipse 3.7 (indigo) and I will use JBoss 4.2.3.GA as a server. As a project build tool i will use maven. Let’s start by creating the most simple web project in eclipse. It will hold the web services implementation (end point). It is just an maven project for an ordinary web application. Nothing special. If you do not wish to use maven that is also fine. You can use what ever tool you like to create a simple web application. I will not go into details here in this post on how to create this simple project. Instead, i will provide you a screen shot of the project structure in my eclipse.Project structure in eclipse.Now let’s create the web service. We will do the ‘ bottom-up approach‘. That means we will develop an implementation class first, and define the WSDL later. So let’s write a simple java POJO class. We will just pretend that our web service takes some kind of car id as a parameter and returns a price for that car. If we pass in a non-existing car id, then the web service will return a corresponding error text. Main elements to spot here are CarWebService interface and CarWebServiceImpl class which actually implements the endpoint interface. Let’s start from the CarWebService interface. Here is the code: package ba.codecentric.webservice;import javax.jws.WebMethod; import javax.jws.WebService;import ba.codecentric.webservice.model.CarResponse;@WebService public interface CarWebService { @WebMethod public CarResponse getCarPrice(String carId);}As you see it is a normal interface definition. Only two things to notice here are two annotations: @WebService and @WebMethod. These annotations belong to the domain of the technology called JAX-WS. JAX-WS is a specification on how to create web services and clients in a way that they are able to communicate with RPC calls and exchange XML based messages. Java has it’s own implementation of JAX-WS and enables us to define a web service end point by using these simple annotations. You can read more about JAX-WS here. Internally this technology in java deals with receiving and parsing XML messages (usually exchanged with SOAP protocol). This shields the developer from many hours of hard work so the developer does not have to spend time writing the code to generate soap message, send it, then receive it on the server side, extract the information from xml, etc.. All this is done internally by JAX-WS mechanism in java. So when you wish to create plain java web service end point on the server, you simply create the interface. Mark the interface with the WebService annotation and mark all the methods in the interface you wish to expose as the remote methods (with WebMethod annotation). These will then become the operations which can be invoked on the interface. In my example i only have one method but there could be many more. Next stop is creating the interface implementation. We have exposed the web service methods (operations of the endpoint). These methods must do something in order for the web service to make sense. In java we do this really simple. We will just create the implementation class for the interface. I will show you the code for the CarWebServiceImpl. package ba.codecentric.webservice.impl;import java.util.HashMap; import java.util.Map;import javax.jws.WebService;import ba.codecentric.webservice.CarWebService; import ba.codecentric.webservice.model.CarResponse;@WebService(endpointInterface = 'ba.codecentric.webservice.CarWebService') public class CarWebServiceImpl implements CarWebService { private final Map<String, Integer> prices = new HashMap<String, Integer>(); public CarWebServiceImpl() { prices.put('audi', Integer.valueOf(10000)); prices.put('bmw', Integer.valueOf(15000)); prices.put('fiat', Integer.valueOf(5000)); } public CarResponse getCarPrice(String carId) { Integer price = prices.get(carId); CarResponse response = new CarResponse(); if(price == null) { response.setCarPrice(-1); response.setStatus('error: no car with id: ' + carId); } else { response.setCarPrice(price.intValue()); response.setStatus('ok'); } return response; }}Only thing to notice here again is the special annotation. Same like in the interface but it only has one extra argument. It is the fully qualified name of the endpoint interface. Nothing else. In the real world this web service would probably have more complicated code. It would take some kind of car id and then it would search for the car in the database. But in here I’ve made much more simple. I have a map for three different car ids and there prices stored with the ids. If you pass in the existing car id to the service (like audi, bmw) you will get response back from the web service on the server. Response will contain status message (ok) and a car price. If you pass in a non-existing car id to the service then you will receive a response with the status error and you will also have a detailed string which is telling you that car you searched for was not found. Car price in this case will be set to -1. Ok. That’s it as far as the web service implementation is concerned. Simple, isn’t it? Only one more thing to do. And this one is even more simple. You need to expose the implementation class as a servlet. You will do this in the web.xml. Here is the code: <servlet> <servlet-name>carWebservice</servlet-name> <servlet-class>ba.codecentric.webservice.impl.CarWebServiceImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>carWebservice</servlet-name> <url-pattern>/ws/car</url-pattern> </servlet-mapping>And we are done. Now we need to package the application and deploy it to JBoss. The JBoss will take care of publishing this endpoint for you so you do not need to worry about it. So go ahead. Deploy your application to JBoss. If you are using maven as a build tool here is how your pom.xml should look like: <build> <finalname>webservices</finalName> <plugins> <plugin> <groupid>org.apache.maven.plugins</groupId> <artifactid>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build>Set the source and target version for the maven compiler to java 6 because of the use of annotations. JBoss has it’s own small web application that allows you to see all the web services which are deployed currently and location of all WSDL files for those web services. You can access this small application from this url: http://localhost:8080/jbossws/services Of course, providing that your JBoss server name is localhost and it’s http port is configured to 8080. Here is the screen shot from my pc which clearly shows that web services we deployed in this example are really running.You can click on the url of the endpoint. The result will be that you will actually see the WSDL of the endpoint. Inside of that WSDL you will see something like <import location=’……’>. The value of the location attribute is the real url of complete WSDL. So go ahead. Also open that url in the browser. Now you should see the entire WSDL (endpoint definitions, operations which can be invoked, messages that are sent to endpoints and received back from endpoints). I hope this makes it easier to see how actually the web services exchanged the data with the clients. Client simply creates the request based on the WSDL file which it gets from the web service. In that WSDL file, the client can see everything that is necessary to communicate with the endpoint. All the rest is taken care of by SOAP protocol and Java’s JAX-WS mechanism. Developer does not have to see an of these operations being invoked. Creating a simple web service client (wsconsume utility) In order to invoke this web service we need to create a client. Client can be a simple java console application. It does not even have to be a web application if you do not want to complicate things. that means you can have a simple java class with the main() method. And all you need in there is a few lines of code and you are done. First thing we need to do here is to generate the so called ‘stub classes’. These classes represent the model request and response classes we use to communicate with the web service. If you remember I’ve created a special wrapper class to return the web service response. But it is not just the model classes which are are in these stub classes. Here you will also find the classes which actually do the invocation of the remote endpoint and some other utility classes. Also you will find some JAXB annotations which are needed when marshaling and un-marshaling java objects to XML message and also the other way round. These stub classes are created based on the WSDL file of the endpoint. If you remember WSDL file contains all the information that a client needs. Based on the WSDL file, we can generate all necessary stub classes (model classes used for communication with the web service and utility classes which are used to facilitate this communication). Lucky for us, JBoss has a small utility program that we will use to generate these classes. We do not have to write a single line of code for these stub classes. And we can also tell this tool to generate the classes immediately in our workspace. Really cool stuff. So let’s give it a shot. The tool is called wsconsume.bat ant it is located in the JBoss folder – bin. for Linux users there is wsconsume.sh. First i will generate a different project for this in Eclipse. I will call it ws-client. It is a normal Java project. You can just choose File -> New -> Java Project and use all default settings. Ok. Now we are ready to create the stub classes. We want the wsconsume utility to put the classes immediately into the src folder for java source files. And we will also tell wsconsume utility the exact name of the package it should use for these classes. My project is located here: D:\JBossTests\jbossWebServiceWorkspace\ws-client. So the command for the wsconsume utlity should be: D:\JBossTests\jboss-4.2.3.GA\bin>wsconsume -v -k -p ws.client.impl -s D:\JBossTests\jbossWebServiceWorkspace\ws-client\src http://127.0.0.1:8080/webservices/ws/car?wsdl Make sure you are executing this command from the jboss bin folder. Otherwise make sure you have the wsconsume.bat file on your path to reach it from any folder. Also make sure your jboss is running and the web services for which you are trying to generate the client, are correctly deployed and running. Let’s explain the parameters i used here: -v: Verbose (show full error stack trace if there is an error); -k: Keep/generate java sources; -p: Package name. The generated classes will immediately get the given package; -s: Source folder. The directory where to put the source files. I used the source folder my client project, which makes sense. And finally we have the URL of the endpoint’s WSDL location. You can open the jboss URL http://localhost:8080/jbossws/services to see all the web services which are currently deployed and see all the WSDL URLs. You can just copy/paste the required WSDL URL to the command prompt for the wsconsume utility . In our case it is the location of the web service we created earlier. Now go to eclipse and refresh you src folder in the new client project. You should now have some classes generated by the wsconsume utility and they should be in the specified package. All we need to do now is to execute this client and send requests to the web services. Just create one more class. I will call it CarWebserviceClient. And i will put it into separate package. And this class will have the normal java main method. Package is ws.client.runner: package ws.client.runner;import ws.client.impl.CarResponse; import ws.client.impl.CarWebService; import ws.client.impl.CarWebServiceImplService;public class CarrWebserviceClient {public static void main(String[] args) { CarWebServiceImplService service = new CarWebServiceImplService(); CarWebService port = service.getCarWebServiceImplPort(); CarResponse audiPrice = port.getCarPrice('audi'); System.out.println('audi price: ' + audiPrice.getCarPrice() + ' EUR; web service status: ' + audiPrice.getStatus());CarResponse fordPrice = port.getCarPrice('ford'); System.out.println('ford price: ' + fordPrice.getCarPrice() + ' EUR; web service status: ' + fordPrice.getStatus()); }} As you see this code above is really simple. You just need to instantiate the client, then obtain the port to the service and that’s it. We can call the web service operation by calling the java method with the same name. Just pass the parameters you wish. You can use audi, bmw, and fiat as hard coded existing values. You can also try to retrieve the price for some non existing car id. Same way I tried in the example above. Of course don’t forget to have your jboss running and web services deployed in order for this to work :-) Well that would be all. This can be a nice starting point to continue your journey into the world of SOAP based web services. This was the most basic example, implemented by using JAX-WS API and with a little help of jboss support for web services. Reference: Core Java Web Services on JBoss from our JCG partner Branislav Vidovi? at the Geek stuff :-) blog....
apache-camel-logo

Apache Camel using Groovy Introduction

From their site, it says the Apache Camel is a versatile open-source integration framework based on known Enterprise Integration Patterns. It might seem like a vague definition, but I want to tell you that this is a very productive Java library that can solve many of typical IT problems! You can think of it as a very light weight ESB framework with ‘batteries’ included. In every jobs I’ve been to so far, folks are writing their own solutions in one way or another to solve many common problems (or they would buy some very expensive enterprisy ESB servers that takes months and months to learn, config, and maintain). Things that we commonly solve are integration (glue) code of existing business services together, process data in a certain workflow manner, or move and transform data from one place to another etc. These are very typical need in many IT environments. The Apache Camel can be used in cases like these; not only that, but also in a very productive and effective way! In this article, I will show you how to get started with Apache Camel along with just few lines of Groovy script. You can certainly also start off with a full Java project to try out Camel, but I find Groovy will give you the shortest working example and learning curve.Getting started with Apache Camel using Groovy So let’s begin. First let’s see a hello world demo with Camel + Groovy. @Grab('org.apache.camel:camel-core:2.10.0') @Grab('org.slf4j:slf4j-simple:1.6.6') import org.apache.camel.* import org.apache.camel.impl.* import org.apache.camel.builder.*def camelContext = new DefaultCamelContext() camelContext.addRoutes(new RouteBuilder() { def void configure() { from('timer://jdkTimer?period=3000') .to('log://camelLogger?level=INFO') } }) camelContext.start()addShutdownHook{ camelContext.stop() } synchronized(this){ this.wait() } Save above into a file named helloCamel.groovy and then run it like this: $ groovy helloCamel.groovy 388 [main] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel 2.10.0 (CamelContext: camel-1) is starting 445 [main] INFO org.apache.camel.management.ManagementStrategyFactory - JMX enabled. 447 [main] INFO org.apache.camel.management.DefaultManagementLifecycleStrategy - StatisticsLevel at All so enabling load performance statistics 678 [main] INFO org.apache.camel.impl.converter.DefaultTypeConverter - Loaded 170 type converters 882 [main] INFO org.apache.camel.impl.DefaultCamelContext - Route: route1 started and consuming from: Endpoint[timer://jdkTimer?period=3000] 883 [main] INFO org.apache.camel.impl.DefaultCamelContext - Total 1 routes, of which 1 is started. 887 [main] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel 2.10.0 (CamelContext: camel-1) started in 0.496 seconds 898 [Camel (camel-1) thread #1 - timer://jdkTimer] INFO camelLogger - Exchange[ExchangePattern:InOnly, BodyType:null, Body:[Body is null]] 3884 [Camel (camel-1) thread #1 - timer://jdkTimer] INFO camelLogger - Exchange[ExchangePattern:InOnly, BodyType:null, Body:[Body is null]] 6884 [Camel (camel-1) thread #1 - timer://jdkTimer] INFO camelLogger - Exchange[ExchangePattern:InOnly, BodyType:null, Body:[Body is null]] ... The little script above is simple but it presented few key features of Camel Groovyness. The first and last section of the helloCamel.groovy script are just Groovy featuers. The @Grab annotation will automatically download the dependency jars you specify. We import Java packages to use its classes later. At the end we ensure to shutdown Camel before exiting JVM through the Java Shutdown Hook mechanism. The program will sit and wait until user press CTRL+C, just as a typical server process behavior. The middle section is where the Camel action is. You would always create a Camel context to begin (think of it as the server or manager for the process.) And then you would add a Camel route (think of it as a workflow or pipeflow) that you like to process data (Camel likes to call these data ‘messages’). The route consists of a ‘from’ starting point (where data generated), and one or more ‘to’ points (where data going to be processed). Camel calls these destination ‘points’ as ‘Endpoints’. These endpoints can be expressed in simple URI string format such as 'timer://jdkTimer?period=3000'. Here we are generating timer message in every 3 secs into the pipeflow, and then process by a logger URI, which will simply print to console output. After Camel context started, it will start processing data through the workflow, as you can observe from the output example above. Now try pressing CTRL+C to end its process. Notice how the Camel will shutdown everything very gracefully. 7312 [Thread-2] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel 2.10.0 (CamelContext: camel-1) is shutting down 7312 [Thread-2] INFO org.apache.camel.impl.DefaultShutdownStrategy - Starting to graceful shutdown 1 routes (timeout 300 seconds) 7317 [Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Route: route1 shutdown complete, was consuming from: Endpoint[timer://jdkTimer?period=3000] 7317 [Thread-2] INFO org.apache.camel.impl.DefaultShutdownStrategy - Graceful shutdown of 1 routes completed in 0 seconds 7321 [Thread-2] INFO org.apache.camel.impl.converter.DefaultTypeConverter - TypeConverterRegistry utilization[attempts=2, hits=2, misses=0, failures=0] mappings[total=170, misses=0] 7322 [Thread-2] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel 2.10.0 (CamelContext: camel-1) is shutdown in 0.010 seconds. Uptime 7.053 seconds. So that’s our first taste of Camel ride! However, we titled this section as ‘Hello World!’ demo, and yet we haven’t seen any. But you might have also noticed that above script are mostly boiler plate code that we setup. No user logic has been added yet. Not even the logging the message part! We simply configuring the route. Now let’s modify the script little bit so we will actually add our user logic to process the timer message. @Grab('org.apache.camel:camel-core:2.10.0') @Grab('org.slf4j:slf4j-simple:1.6.6') import org.apache.camel.* import org.apache.camel.impl.* import org.apache.camel.builder.*def camelContext = new DefaultCamelContext() camelContext.addRoutes(new RouteBuilder() { def void configure() { from('timer://jdkTimer?period=3000') .to('log://camelLogger?level=INFO') .process(new Processor() { def void process(Exchange exchange) { println('Hello World!') } }) } }) camelContext.start()addShutdownHook{ camelContext.stop() } synchronized(this){ this.wait() } Notice how I can simply append the process code part right after the to('log...') line. I have added a ‘processor’ code block to process the timer message. The logic is simple: we greet the world on each tick. Making Camel route more concise and practical Now, do I have you at Hello yet? If not, then I hope you will be patient and continue to follow along for few more practical features of Camel. First, if you were to put Camel in real use, I would recommend you setup your business logic separately from the workflow route definition. This is so that you can clearly express and see your entire pipeflow of route at a glance. To do this, you want to move the ‘processor’, into a service bean. @Grab('org.apache.camel:camel-core:2.10.0') @Grab('org.slf4j:slf4j-simple:1.6.6') import org.apache.camel.* import org.apache.camel.impl.* import org.apache.camel.builder.* import org.apache.camel.util.jndi.*class SystemInfoService { def void run() { println('Hello World!') } } def jndiContext = new JndiContext(); jndiContext.bind('systemInfoPoller', new SystemInfoService())def camelContext = new DefaultCamelContext(jndiContext) camelContext.addRoutes(new RouteBuilder() { def void configure() { from('timer://jdkTimer?period=3000') .to('log://camelLogger?level=INFO') .to('bean://systemInfoPoller?method=run') } }) camelContext.start()addShutdownHook{ camelContext.stop() } synchronized(this){ this.wait() } Now, see how compact this workflow route has become? The Camel’s Java DSL such as 'from().to().to()' for defining route are so clean and simple to use. You can even show this code snip to your Business Analysts, and they would likely be able to verify your business flow easily! Wouldn’t that alone worth a million dollars?How about another demo: FilePoller Processing File polling processing is a very common and effective way to solve many business problems. If you work for commercial companies long enough, you might have written one before. A typical file poller would process incoming files from a directory and then process the content, and then move the file into a output directory. Let’s make a Camel route to do just that. @Grab('org.apache.camel:camel-core:2.10.0') @Grab('org.slf4j:slf4j-simple:1.6.6') import org.apache.camel.* import org.apache.camel.impl.* import org.apache.camel.builder.* import org.apache.camel.util.jndi.*class UpperCaseTextService { def String transform(String text) { return text.toUpperCase() } } def jndiContext = new JndiContext(); jndiContext.bind('upperCaseTextService', new UpperCaseTextService())def dataDir = '/${System.properties['user.home']}/test/file-poller-demo' def camelContext = new DefaultCamelContext(jndiContext) camelContext.addRoutes(new RouteBuilder() { def void configure() { from('file://${dataDir}/in') .to('log://camelLogger') .to('bean://upperCaseTextService?method=transform') .to('file://${dataDir}/out') } }) camelContext.start()addShutdownHook{ camelContext.stop() } synchronized(this){ this.wait() } Here you see I defined a route to poll a $HOME/test/file-poller-demo/in directory for text files. Once it’s found it will log it to console, and then process by a service that transform the content text into upper case. After this, it will send the file into $HOME/test/file-poller-demo/out directory. My goodness, reading the Camel route above probably express what I wrote down just as effective. Do you see the benefits here?What’s the ‘batteries’ included part. If you’ve used Python programming before, you might have heard the pharase that they claim often: Python has ‘batteries’ included. This means their interpreter comes with a rich of libaries for most of the common programming need. You can often write python program without have to download separated external libraries. I am making similar analogies here with Apache Camel. The Camel project comes with so many ready to use components that you can find just about any transport protocals that can carry data. These Camel ‘components’ are ones that support different ‘Endpoint URI’ that we have seen in our demos above. We have simply shown you timer, log, bean, and file components, but there are over 120 more. You will find jms, http, ftp, cfx, or tcp just to name a few. The Camel project also has an option for you to define route in declarative xml format. The xml is just an extension of a Spring xml config with Camel’s namespace handler added on top. Spring is optional in Camel, but you can use it together in a very powerful way. Reference: Getting started with Apache Camel using Groovy from our JCG partner Zemian Deng at the A Programmer’s Journal blog....
oracle-glassfish-logo

GlassFish: How to deploy a war file

Before trying this out make sure you have installed GlassFish in your machine. Installation is just easy as downloading the zip archive from here and unzipping it to a desired location. Creating a new domain Open up a terminal, change directory to the GlassFish installation directory and run following.       bin/asadminThis will enable you to use asadmin tool. Now execute the following command to create a new domain. after running this command you will probably have to give admin password and master password. create-domain --adminport 5000 --profile developer --user admin domain2Now open up another terminal and change directory to [glassfish-installation]/domains/ and you will see the newly created domain2 has appeared there.Open up a browser and go to http://localhost:5000/. This will bring you the GlassFish GUI admin console. This is one place you can deploy your war file. But in this post I’m not much focusing on it, instead I will show you how to do this using the command line. But GUI lovers, for any consolation I have put some screenshots which you can follow if you prefer the GUI way.In case you want to delete a domain use the following command. delete-domain domain2Starting the domain To start domain2 run following command. start-domain domain2Deploying a war file Use the following command to deploy your war file. deploy --port 5000 --host localhost /home/pavithra/workspace/NewDemoService/WebServicesJaxWs/NewDemoService.warAfter deploying the war file I can access the WSDL file I want to access using the URL http://localhost:8080/NewDemoService/NewDemoService?WSDLTo change default 8080 (HTTP) port which specifies where the web application context roots are available for a Web browser to connect to, you can use the –instanceport parameter when creating the domain. See the following command. create-domain --adminport 5000 --profile developer --user admin --instanceport 9000 domain2Undeploying a war file To undeploy NewDemoService.war file you need to use the following command. Note that here you don’t have to use the full name but literal “NewDemoService”. undeploy --port 5000 --host localhost NewDemoServiceStopping a domain To stop the domain “domain2″ use the following command. stop-domain domain2After this if you try to deploy to this particular domain, it will complain. Auto Deploy To perform auto deploy, copy NewDemoService.war file in to [glassfish-installation-directory]/domains/domain2/autodeploy directory. If autodeploy succeeds, you will see NewDemoService.war_deployed has created. This will deploy your war file automatically.  Reference: How to deploy a war file using GlassFish from our JCG partner Pavithra Siriwardena at the EVIAC blog. ...
Java Code Geeks and all content copyright © 2010-2015, 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 our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close