What's New Here?


Overqualified is Overdiagnosed

I’ve been inspired by comments on prior articles to discuss the sensitive topics of ‘overqualification’ and ageism. My Why You Didn’t Get The Job and Why You Didn’t Get The Interview posts were republished on a few sites, resulting in some active debates where at some point a participant states that the real reason that they weren’t hired was that they are overqualified for all the jobs out there, or they were victims of ageism. In my opinion and experience recruiting in the software engineering world, the term overqualified is used too widely by companies (and then inaccurately cited by rejected candidates), and claims of alleged ageism are often something else entirely. Before we begin, I acknowledge that companies want to hire cheaper labor when possible, and some shops care less about quality products than others. And for the record, I’m over 40. By saying you are overqualified for jobs, what are you really saying? “I am more skilled or more experienced than the job requires.“ That feels kind of good, doesn’t it? SPOUSE: How did the interview go? JOB SEEKER: I didn’t get the job. SPOUSE 1: Oh, I’m sorry. What happened? JOB SEEKER: Unfortunately, it turns out my skills are simply too strong. Of course rejection hurts, but to tell your spouse (and yourself) that you were turned down because you were too skilled or too experienced is much less bruising on the ego than the alternative. For companies looking to eliminate candidates, using the word overqualified may take some of the sting and fear of retribution out of the rejection. But is it true? Think about this scenario for a second. You are trying to hire a software developer and you estimate that someone with say five years of experience should be able to handle the duties effectively. A candidate is presented with fifteen years of experience that has all the attributes you are seeking. This person should theoretically perform the tasks quicker and even take on some additional workload. Do you really think a company would not hire this person simply because he/she has those additional years of experience? I would argue that is rarely the case. Question: Is ‘overqualified’ a code word used by managers/HR to mean other things? Answer: ALMOST ALWAYS What can overqualified actually mean? listed in order from most likely to least likely, IMOOverpaid/over budget – If your experience > what is required, it generally becomes a problem when your salary requirements are above what is budgeted. It’s not that you are classified as overpaid in your current role, but that you would be overpaid for the level of responsibility at the new job. I list this as the most likely culprit because I often see companies initially reject a candidate as overqualified, then hire that same person because of a lack of less experienced quality talent. Stagnant – Candidates who have worked for many years as a developer in a technically stagnant and regulated environment will often not thrive in less regulated, more technically diverse firms. The conventional wisdom, right or wrong, is that you can’t release the zoo lions back into the jungle once they’ve been tamed. ‘Overskilled’ – If your skills > what is necessary for the job, an employer may fear that the lack of challenges provided will bore you into looking for more interesting work in the future. Hiring a tech lead to do bug fixes could lead to a short stint. There is emerging evidence that shows skilled workers do not exit less challenging jobs quickly or in high numbers, but hiring managers are not quite ready to abandon the traditional line of thinking. Threatening – If your experience > those conducting the interviews, there could be some fear that you could be a competitor for future opportunities for promotion. If a start-up is yet to hire a CTO, the highest geek on that firm’s food chain may be jockeying for the role. This may sound a bit like a paranoid conspiracy theory, but I genuinely believe it is prevalent enough to mention. Too old – Ageism is a real problem, but in my experience in the software world, ageism is also widely overdiagnosed by candidates who think the problem is their age when in actuality it is their work history. Most of the self-diagnosed claims of ageism that I hear are from candidates who spent perhaps 20+ years working for the same company and have not focused on keeping their skills up to date (see stagnant above). I can’t say that I’ve ever heard a claim of ageism from a candidate that has moved around in their career and stayed current with technology. The problem often isn’t age, it is relevance.Some of the best and most accomplished/successful software engineering professionals that I know are over 50, which is older than some of the candidates I hear claiming possible ageism. One trait that the overwhelming majority of these engineers have in common is that they didn’t stay in any one place for too long to stagnate. I don’t think that is a coincidence. If you are an active job seeker that is continuously hearing that you are overqualified, what can you do to improve your standing?Rethink – Try to investigate which of the meanings of overqualified you are hearing most often. Is your compensation in line with what companies are paying for your set of qualifications? Do you present yourself in interviews as someone who may become easily bored when your work is less challenging? Are you making it clear in interviews that you want the job, and you explain why you want the job? Retool – Make sure your skills are relevant and being sought by companies. Invest time to learn an emerging technology or developing some niche specialty that isn’t already flooded. Remarket – Write down the top reasons you think a company should hire you, and then check to see if those reasons are represented in your job search materials (resume, email application, cover letters). Find out what was effective for your peers in their job search and try to implement new self-promotion tactics. Reboot and refresh – Take a new look at your options beyond the traditional career paths. Have you considered consulting or contracting roles where your guidance and mentoring skills could be justified and valued for temporary periods? Are there emerging markets that interest you?Terms like ‘overqualified’ and ‘not a fit’ are unfortunately the laziest, easiest, and safest ways that companies can reject you for a position, and they almost always mean something else. Discovering the real reason you were passed up is necessary to make the proper adjustments so you can get less rejections and more offers. Reference: Overqualified is Overdiagnosed from our JCG partner Dave Fecak at the Job Tips For Geeks blog....

Rewrite to the edge – getting the most out of it! On GlassFish!

A great topic for modern application development is rewriting. Since the introduction of Java Server Faces and the new lightweight programming model in Java EE 6 you are struggling with pretty and simple, bookmarkable URLs. PrettyFaces was out there since some time and even if it could be called mature at the 3.3.3 version I wasn’t convinced. Mainly because of the fact that I had to configure it in xml. If you ever did a JSF project you know that this is something you do on top later on. Or never. With the last option being the one I have seen a lot. Rewrite is going to change that. Programmatic, easy to use and highly customizable. Exactly what I was looking for.Getting StartedNothing is easy as getting started with stuff coming from one of the RedHat guys. Fire up NetBeans, create a new Maven based Webapp, add JSF and Primefaces to the mix and run it on GlassFish. First step for adding rewriting magic to your application is to add the rewrite dependencies to your project. <dependency> <groupId>org.ocpsoft.rewrite</groupId> <artifactId>rewrite-servlet</artifactId> <version>1.1.0.Final</version> </dependency>That isn’t enough since I am going to use it together with JSF, you also need the jsf-integration. <dependency> <groupId>org.ocpsoft.rewrite</groupId> <artifactId>rewrite-integration-faces</artifactId> <version>1.1.0.Final</version> </dependency>Next implement your own ConfigurationProvider. This is the central piece where most of the magic happens.Let’s call it TricksProvider for now and we also extend the abstract HttpConfigurationProvider. A simple first version looks like this: public class TricksProvider extends HttpConfigurationProvider { @Override public int priority() { return 10; }@Override public Configuration getConfiguration(final ServletContext context) { return ConfigurationBuilder.begin() .addRule(Join.path("/").to("/welcomePrimefaces.xhtml")); } }Now you have to register your ConfigurationProvider. You do this by adding a simple textfile named org.ocpsoft.rewrite.config.ConfigurationProvider to your applications /META-INF/services/ folder. Add the fully qualified name of your ConfigurationProvider implementation to it and you are done. If you fire up your application. The Rewriting BasicsWhile copying the above provider you implicitly added your first rewriting rule. By requesting http://host:8080/yourapp/ you get directly forwarded to the Primefaces welcome page generated by NetBeans. All rules are based on the same principle. Every single rule consists of a condition and an operation. Something like “If X happens, do Y”. Rewrite knows two different kinds of Rules. Some preconfigured ones (Join) starting with “addRule()” and a fluent interface starting with defineRule(). This is a bit confusing because the next major release will deprecate the defineRule() and rename it to addRule(). So most the examples you find (especially the test cases in the latest trunk) are not working with the 1.1.0.Final. Rewrite knows about two different Directions. Inbound and Outbound. Inbound is most likely working like every rewriting engine you know (e.g. mod_rewrite). A request arrives and is forwarded or redirected to the resources defined in your rules. The Outbound direction is little less. It basically has a hook in the encodeURL() method of the HttpServletRequest and rewrites the links you have in your pages (if they get rendered with the help of encodeURL at all). JSF is doing this out of the box. If you are thinking to use it with JSPs you have to make sure to call it yourself. Forwarding .html to .xhtml with some magicLet’s look at some stuff you could do with rewrite. First we add the following to the TricksProvider: .defineRule() .when(Direction.isInbound() .and(Path.matches("{name}.html").where("name").matches("[a-zA-Z/]+"))) .perform(Forward.to("{name}.xhtml"));This is a rule which is looking at inbound requests and checks for all Patch matches {name}.html which confirm to the regular expression pattern [a-zA-Z/]+ and Forwards those to {name}.xhtml files. If this rule is in place all requests to http://host:8080/yourapp/something.html will end up being forwarded to something.xhtml. Now your users will no longer know that you are using fancy JSF stuff underneath and believe you are working with html :) If a url which isn’t matching the regular expression is requested, for example something like http://host:8080/yourapp/something123.html this simply isn’t forwarded and if the something123.html isn’t present in your application you will end up receiving a 404 error. Rewriting Outbound LinksThe other way round you could also add the following rule: .defineRule() .when(Path.matches("test.xhtml") .and(Direction.isOutbound())) .perform(Substitute.with("test.html"))You imagine what this is doing, right? If you have a facelet which contains something like this: <h:outputLink value="test.xhtml">Normal Test</h:outputLink>The link that is rendered to the user will be rewritten to test.html. This is the most basic action for outbound links you will ever need. Most of the magic happens with inbound links. Not a big surprise looking at the very limited reach of the encodeURL() hook. The OutputBufferThe most astonishing stuff in rewrite is called OutputBuffer. At least until the release we are working with at the moment. It is going to be renamed in 2.0 but for now let’s simply look at what you could do. The OutputBuffer is your hook to the response. Whatever you would like to do with the response before it actually arrives at your client’s browser could be done here. Thinking about transforming the markup? Converting css? Or even GZIP compression? Great, that is exactly what you could do. Let’s implement a simple ZipOutputBuffer public class ZipOutputBuffer implements OutputBuffer {private final static Logger LOGGER = Logger.getLogger(ZipOutputBuffer.class.getName());@Override public InputStream execute(InputStream input) { String contents = Streams.toString(input); LOGGER.log(Level.FINER, "Content {0} Length {1}", new Object[]{contents, contents.getBytes().length}); byte[] compressed = compress(contents); LOGGER.log(Level.FINER, "Length: {0}", compressed.length); return new ByteArrayInputStream(compressed); }public static byte[] compress(String string) { ByteArrayOutputStream os = new ByteArrayOutputStream(string.length()); byte[] compressed = null; try { try (GZIPOutputStream gos = new GZIPOutputStream(os)) { gos.write(string.getBytes()); } compressed = os.toByteArray(); os.close(); } catch (IOException iox) { LOGGER.log(Level.SEVERE, "Compression Failed: ", iox); } return compressed; } }As you can see, I am messing around with some streams and use the java.util.zip.GZIPOutputStream to shrink the stream received in this method. Next we have to add the relevant rule to the TricksProvider: .defineRule() .when(Path.matches("/gziptest").and(Direction.isInbound())) .perform(Forward.to("test.xhtml") .and(Response.withOutputBufferedBy(new ZipOutputBuffer()) .and(Response.addHeader("Content-Encoding", "gzip")) .and(Response.addHeader("Content-Type", "text/html"))))An inbound rule (we are not willing to rewrite links in pages here .. so it has to be inbound) which adds the ZipOutputBuffer to the Response. Also take care for the additional response header (both) unless you want to see your browser complaining about the content I have mixed up :) That is it. The request http://host:8080/yourapp/gziptest now delivers the test.xhtml with GZIP compression. That is 2,6KB vs. 1,23 KB!! Less than half of the size !! It’s not very convenient to work with streams and byte[]. And I am not sure if this will work with larger page sizes in terms of memory fragmentation, but it is an easy way out if you don’t have a compression filter in place or only need to compress single parts of your application. Enhance Security with RewriteBut that is not all you could do: You could also enhance the security with rewrite. Lincoln has a great post up about securing your application with rewrite. There are plenty of possible examples around how to use this. I Came up with a single use-case where didn’t want to use the welcome-file features and prefer to dispatch users individually. While doing this I would also inspect their paths and check if the stuff they are entering is malicious or not. You could either do it with the .matches() condition or with a custom constraint. Add the following to the TricksProvider: Constraint<String> selectedCharacters = new Constraint<String>() { @Override public boolean isSatisfiedBy(Rewrite event, EvaluationContext context, String value) { return value.matches("[a-zA-Z/]+"); } };And define the following rule: .defineRule() .when(Direction.isInbound() .and(Path.matches("{path}").where("path").matches("^(.+)/$") .and(Path.captureIn("checkChar").where("checkChar").constrainedBy(selectedCharacters)))) .perform(Redirect.permanent(context.getContextPath() + "{path}index.html"))Another inbound modification. Checking the path if it is has a folder pattern and capturing it in a variable which is checked against the custom constraints. Great! Now you have a save and easy forwarding mechanism in place. All http://host:8080/yourapp/folder/ request are now rewritten to http://host:8080/yourapp/index.html. If you look at the other rules from above you see, that the .html is forwarded to .xhtml … and you are done! Bottom LineI like working with rewrite a lot. It feels easier than configuring the xml files of prettyfaces and I truly enjoyed the support of Lincoln and Christian during my first steps with it. I am curious to see what the 2.0 is coming up with and I hope that I get some more debug output for the rules configuration just to see what is happening. The default is nothing and it could be very tricky to find the right combination of conditions to have a working rule. Looking for the complete sources? Find them on github. Happy to read about your experiences. Where is the GlassFish Part?Oh, yeah. I mentioned it in the headline, right? That should be more like a default. I was running everything with latest GlassFish so you can be sure that this is working. And NetBeans is at 7.2 at the moment and you should give it a try if you haven’t. I didn’t came across a single issue related to GlassFish and I am very pleased to stress this here. Great work! One last remark: Before you are going to implement the OutputBuffer like crazy take a look at what your favorite appserver has in stock already. GlassFish knows about GZIP compression already and it simply can be switched on! Might be a good idea to think twice before implementing here. Reference: Rewrite to the edge – getting the most out of it! On GlassFish! from our JCG partner Markus Eisele at the Enterprise Software Development with Java blog....

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....

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 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....

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 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....

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 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 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 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....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

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

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

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