Featured FREE Whitepapers

What's New Here?


7 Brain Tips for Software Developers

Estimated Reading Time: 10-15 minutes EDITORIAL NOTE: This is an article that I am really glad to have featured on Java Code Geeks and one that I think is long overdue. It will explain how to leverage and better utilize our greatest asset as programmers, and that is of course, our brain. We are intellectual workers and without an optimally working brain, we produce substandard work. We all know this on an abstract, theoretical basis, but still, we rarely do the stuff that will help our brains function better. We always think about the latest cool technology, but we rarely stop and take care of the fundamentals. And boy, as programmers, we are way off at this. From having a love affair with the vending machine, to constantly being stressed and “burned out”. From regarding extra hours as a badge of honor, to totally neglecting our bodies. So, it is time to restore the order and help you master what billions of years of evolution have gifted you with: your human brain. Enjoy! It was only some years ago that I realized that whatever I do, think, feel and have in my life, are in direct proportion of the performance of my brain. I immersed myself in books, videos and articles on what improves our brain’s performance, and how one can turn around almost any situation no matter how bad it seems. By starting to implement these tips I’m going to share with you, I literally saw every aspect of my life transforming, change happening with incremental speed, while at the same time feeling more happy and fulfilled than ever. I had cracked the code. Now, 2 years after, I can juggle with all the areas of my life simultaneously, improving them all day by day, week by week. I really don’t say that to impress you, but rather to make a point: that when you start improving your brain and how it works, everything will be possible. Positive States = Resourceful states First of all, one of the first things I learned in my journey, it’s something I got from Tony Robbins: everything is driven by emotions. If businesses rise or fall because of their leaders, leaders rise or fall because of their emotions. Emotions are what drive people. Emotions are what enable or disable different parts of our brain. And there are no positive or negative emotions, but rather “resourceful” or “unresourceful” states. I am certain that we all have experienced some times that everything seemed to click, to say and do the right thing at the right time, and everything seemed brilliant. Right then, we were experiencing a resourceful state. That was a Genius state. A state in which our brain was open and creative, and was finding whatever was needed, when it was needed. I am also certain that all of us have experienced times that our brain is like dead. We knew that we know the answer, but we couldn’t remember it – or better, access it. We were being stupid and doing/saying stupid things. When we were saying things that we were thinking afterwards “what was I thinking?! That wasn’t me!”. We were in a stupid state! And that was an example of an unresourceful state that we had. Emotions can definitely block our brain from finding what and when is needed. I understood that Creativity and Resourcefulness are what we need at all times, in order to grow, evolve and perform correctly. And so I immersed myself even more on that subject, coming up a year later with a book on 33 ways to boost our brain’s natural creative capabilities. What are the states in which your brain is working in full speed? What are the states in which your brain shows some of its genius? What are the states in which everything seems to click? But most importantly: What can you do in order to enter these Resourceful States? I will give you 7 ways, although there are countless more, and actually this is the base for the whole book I recently published on Amazon (you can find it on my site): Tip 1: Imbue Passion in your Daily Life Start doing more of what you love doing, and stop doing things that you hate doing. Simple as that. Have more fun with your loved ones. Go on trips, and escape once in a while (more on that later). Find a PURPOSE on your work. Read Your Body of Work of Pamela Slim. Understand that everything you’ve done up until now had a bigger purpose. And find yours. Aligning a job you love doing with a bigger purpose, is the secret key not only to happiness, but also to Mastery, immense Contribution and potentially, Wealth. One way to add more passion (which I love!) is to start always having 1-3 side-projects. Of course you’ll have your main project with the big deadline staring at you, but you can also create some side-projects for yourself, things you want to achieve, things that really fill you up with juicy emotions, things that – what the heck – may someday become your main projects. If you do them on your free time, they won’t stress you out anyway and you’ll do them just for the fun of it. That’s the point. To recreate you and give you some purpose, some passion, some reason for being and going through any hardships. Start a hobby you always wanted – dancing, sketching, drawing, creating art on photoshop or 3D studio, or whatever. Start a sport or a martial art. Start learning things you always wanted through online learning platforms (like JCG Academy, Coursera, Class-Central, Udemy, etc.). Another way is to add passion in your daily life is by simply PRACTICING passion! Speak about things you are passionate about. Travels and adventures, stories you’ve lived and long forgotten that you are proud and passionate about. Speak louder and with more passion in your voice. Laugh harder. Walk with complete determination and like you have a set purpose. Read The Alchemist of Paulo Coelho (my favorite book of all times). But how can you possibly exude passion when you are all worn and stressed out? So that’s the main point of the rest of the article. All the tips below are targeting on reducing the stress from your life and from your brain, so you can allow it to work at its optimum, and allow the space for creativity, novel and breakthrough ideas and to arise. First a foremost, a lesson from nature herself: Tip 2: Work in Cycles and Pulses, like Nature does I’m writing these lines as I lay on the beach. It’s early in the morning. We came with my friends yesterday night with a bunch of beers, and slept here on the beach till the sunrise. It’s one of the best experiences ever. After a long week of pushing the envelope, delivering all the work and value I possibly could, and making major progress towards all of my goals – on my health, on my fitness, on my relationships, University, career and finances – now it’s time for pause, renewal and rejuvenation. The first thing I saw when I woke up today was this heaven. And this is me walking the walk on the second tip I want to share with you, that will drastically improve your brain, and if consistently applied in every level of your life, it would certainly and totally transform your whole reality. And this made me think. A lot. On the one hand, you see, people believe that stress is bad. I can argue that. Stress is a very good thing. It pushes us to break through our own walls and limitations, it forces us to leave the couch and take some action. It forces change and improvement. It forces our inner power to rise to the surface, and we discover hidden strength that we weren’t even aware of it. “Pressure creates Diamonds” The problem in our culture is not about having too much stress. On the contrary, all the great breakthroughs and evolution that has happened since the dawn of time is because of some form of stress, that forced things to change. The problem lies in not recovering after stress. All the progress and growth comes in the relaxation after the stressful period, after the deadline ends and your brain starts relaxing. We need this recovery period, in order to be able to handle the next stressful period. Every athlete knows that it’s in those resting periods that their muscles are rebuilt and grow in capability. And this led me to another realization: Everything in nature works in pulses and cycles. Our heart beats in pulses. Our brain, our endocrine system, and everything in our body, the seas, the earth, our planet, the moon, our solar system and everything in universe, works in cycles and pulses. I had first met this “Sprinter” model by the writer of The Monk who sold his Ferrari, Robin Sharma. Schedule time for relaxation and renewal. It will VASTLY improve your focus, your mood, and reconnect you with the grander scheme of your life. It will make your life juicier, and at the same time will leave you with enough space to improve your own self. This will allow your brain to switch gears into the creative, pause & plan mode. As long as you are working, no worthy ideas will come. But you’ve may noticed that when you start daydreaming or going for a walk, or on vacation, this is when most of your big ideas come. It is in those periods of relaxation that creativity arises and offers you a whole new field of possibilities and solutions, that if applied could take your relationships, your career or your finances to a whole another level. You can start applying this pattern in your days by having a predetermined time that you STOP working and start relaxing and rejuvenating, so that you’ll have in mind that this is when is you’ll be able to relax, not now. While relaxing, it’s FORBIDDEN to work, otherwise it’s not relaxing and your brain knows it. Apply it in your weeks by having 1-2 days that no work is allowed. It’s not true relaxation if you work or do the things you do the other days!!! Do things that really re-create you. Apply it in your months by taking a week off every 3-4 weeks if it is possible. When you overdeliver value the weeks that you are working then you deserve a week off to renew. Remember: that’s not slacking. That’s not inertia. This is where you grow in your capability, and this is entering the field of pure potentiality and creativity. According to Parkinson’s Law, “your work will expand to fit the time available”. So if you set a timetable, and do your best to make it happen, you could really fit the work of weeks into days. It’s said that work and women follow the law of gas volume: they will expand to fill the volume available. And it’s completely true for both of them. You can check out also this article on productivity tips for software developers, especially those on batching and timetables, and reducing the distractions, as well as this article on Weekly Scheduling. Tip 3: Focus is more important than Intelligence “The mark of a person who is in control of consciousness is the ability to focus attention at will, to be oblivious to distractions, to concentrate as long as it takes to achieve a goal, and not longer. And the person who can do this usually enjoys the normal course of everyday life.” ~ Mihaly Csikszentmihalyi from his book Flow What’s the point of being smart if you can’t control what you are focusing on? Laser-like focus is what distincts excellence from mediocrity. People who succeed in whatever area of their life, are masters of their focus on that specific area, and they are guarding it like their most precious gift. They know what specific things they have to do in order to get “in the zone” or “flow”, and what things might get them out of it, so they proactively block these in advance. When you lose your focus, you lose your power. We are living in an era of distraction. Advertisements, demanding people, social media notifications, everything is trying to grab your attention. But when you lose your focus even for a second, you get “off the zone”, and most of the times you will need many minutes in order to refocus again. The whole area of Emotional Intelligence is about learning how to control our emotions, but in reality, it’s more about learning how to control your focus. What we focus on, is what we experience. So everything is a matter of focus or better, a matter of entering a state of flow, and maintaining it as long as we want. “Lack of direction [of focus], not lack of time, is the problem. We all have twenty-four hour days.” ~ Zig Ziglar Indeed, we all have 24 hours in our days. But then, why some people become Leonardo Da Vincis, Steve Jobses, Bill Gateses, Michael Dells, Brendan Eichs, Larry Pages and Sergey Brins, while others die in mediocrity and invisible? They are smarter? The had more resources when they begun? They knew what to do and how to do it? Of course not. It was what they FOCUSED on in these 24 hours that made the whole difference. There are many ways we can train our brain to improve its focusing abilities. The first is the questions I aforementioned, because what we ask (focus on), we receive. I will give you one more, which is by far the most powerful way: One-pointed Meditation Meditation although is something that most of us here in the Westernized world thing as voodoo stuff and weird things some monks do in the East, here is a quote I found recently… From Fortune: “Meditation devotees include junk-bond-king-turned-philanthropist Mike Milken; Bill George, the former Medtronic CEO; ad industry mogul Renetta McCann; and NBA coach Phil Jackson. Silicon Valley is full of meditators, such as Marc Benioff, the CEO of Salesforce.com, and Larry Brilliant, head of Google’s philanthropic efforts. Naturally, a crew of Google employees has organized twice-weekly open meditation hours, at which it has hosted Tibetan monks and a team of mind-science researchers.” Ok, now that I have your attention, let’s explain in simple terms what this meditation thing is all about: Meditation will boost your ability to focus on one thing for extended periods of time, while at the same time doing some incredible things at your body: it boosts melatonin (the sleep hormone – improving the quality of your sleep), improve your memory, improve your ability to control your emotions, and also put you in a Creative / Resourceful state, making it easier for you to download new ideas and have breakthroughs. When you meditate it’s like connecting to a database of Ideas and start downloading. Pieces come together, you link together seemingly different things, and you come up with ideas that if consistently acted upon, could really bring you millions. HOW do you do it? You sit in a comfortable chair, with your spine straight so that the brain’s bloodflow is maximum. You close your eyes, select a thing to have as an anchor for your focus – maybe your breath, your heartbeat, or a sound, or a word or something, and you focus only on that one thing. When your mind wonders – and it will – don’t start blaming yourself or whatever. It’s what is supposed to happen. You just return your focus on your anchor. And again. And again. And again. For as long as you like. Every time you return your focus on your anchor is like taking a push-up for your focus. You strengthen it with each repetition. And that’s it. Weird eh? Don’t think so. Try it. Just start with 5 minutes or just 1 minute, but do it consistently for some days. Remember: Consistency is more important than Intensity. Do it as long as you feel comfortable doing it, but schedule a chunk of time for it and do it daily. For more on the benefits of meditation, you can read a post I had written some months ago: The 7 most powerful benefits of Meditation, and why you should start it today! Its most staggering scientifically proven result is the major reduction of stress, and improvement of your sleep’s quality. You can dig deeper in the above article if you want to find out more. You can also meditate while at the same time doing the next tip, which is… Tip 4: Focused, Diaphragmatic Breathing Breathing has been shown to be THE fastest way to amp your brain performance. Why? Neuroscientists and peak performance scientists tell us on their recent findings that the function of our brain is controlled by the variance of the rate of our heartbeat. This is called HRV or Heart Rate Variance, and it’s the variance of the rate in which our heart’s BPM is changing. When we are frightened or depressed, it’s not just the depth of our breathing that reduces the oxygenation of our brain, but it’s also the loss of rhythm of our breath that reduces our ability to think clearly and perform as good as we want to. When our breath is rhythmic and even, then our HRV follows a beautiful sinusoidal curve and THIS is when our brain performs at its best. Its not the rate at which our heart is beating. It can beat fast and we may be fully excited or scared as hell. And it can be slow and we may be serene and peaceful but with our mind going 200mph, or clinically depressed. The sole difference between our ability to think clearly and perform at our best is in our ability to keep a steady and even breathing rhythm and a beautiful harmonious HRV. The exercise that you might want to try here, is to take some breaths rhythmically and evenly, like 5″ inhale and 5″ exhale, or 6″-6″, or 8″-8″, or even 2″-2″ or 1″-1″ if you want (these fast breathing is called “fire breathing” and it’s a breathing exercise in yoga to boost your energy). Do it for 5 minutes, or 100 breaths or so. You can build up from there. Do it daily (even twice or thrice daily if you like), in order to habitualize and ingrain into your nervous system this breathing pattern, so it can become more natural and effortless. By doing this breathing exercise, you also meditate at the same time, either you want it or not, because you are focusing on one thing, and every time your mind wanders, you have to bring it back to your breath counting. So you gain all the benefits from the meditation tip too! This exercise will surely boost your brain’s clarity, focus and also give you more energy and vitality, by further reducing your body’s stress levels. Try it out, I’m sure you’ll love it. If you want to dive deeper on this breathing + HRV tip, you can start your research here. Tip 5: Skip a meal or two If you didn’t know that our digestive system is the most energy consuming system of our body, it’s time to learn it. What you eat, how you eat it, and how much you eat, will influence big time your brain’s clarity and focus. And so it will also influence your results and your income. There are two states for our digestive system: Fasted and Fed. In our culture today we are used to being in fed state all the time. And it’s not how our bodies are designed to work after centuries and centuries of evolution. Most of us don’t know what real hunger is. It’s to not have eaten anything for the past weeks and still not to know when you will get something to eat. What we think of as hunger, is simply our psychological need to eat. We eat by the clock and in the simplest hint our gut is about to empty. In the recent years many scientists are studying the crazy benefits of intermittent fasting ie fasting for 14-24 hours. You can benefit by doing it just for 14 (if woman) or 16 (if man) hours, just once per week (or like me, daily! – it’s called “just skip breakfast” method). Besides the crazy benefits it has for our health and body (lower body fat, increased fat burning, increase in human Growth Hormone and much more), by just giving our digestive system a short break, there is also a slight side-effect I noticed when fasting. After my research, it seems like everybody noticed that fasting also gives you crazy amounts of mental clarity and focus, amplifying your overall productivity. Not to mention the extra time you get for not having to buy / cook / order / eat and digest food. By fasting you will notice that there will be less distractions. You will notice the brain fog you were used in having all that time will lift and leave you some space for clear thinking. This brain fog is the result of the ups and downs of our blood’s levels of glucose. By fasting, or by eating some healthy oils (like coconut oil), you blunt more and more these ups and downs, having a more stable brain performance. Fasting has been shown scientifically to increase the production of Brain-Derived Neurotrophic Factor (BDNF), brain protein that is instrumental to neurogenesis (development of new neurons) and the formation of new synapses (connections between neurons). Essentially, your body while fasted is making you smarter in order to find some food, but of course, you can use that clarity and focus wherever you want! The human body (and ESPECIALLY the brain) is highly reactive and affected to the kind of stimuli we give it. Just remember this quote: “sleep is more important than eating” and repeat it over and over, till you start believing it. It’s THAT important. Just remember to drink more non caloric fluids (especially water or tea, but don’t overdo it with coffee) because without food in the gut, there is not much water retention and you can easily dehydrate yourself. You can learn more for intermittent fasting here and here. Remember:You can only live a few seconds without Oxygen. You can only live 3-4 days without water. You can only live some days more without sleep (but with serious brain dysfunctions and problems). You can live some weeks and in most cases more than a month without food.So let this list clarify your priorities, and you can research it further if you like. Which leads us to the next tip: Tip 6: Sleep is MORE important than Eating We all know that sleep is needed to regenerate our body, but what it especially regenerates, is the brain, so it may continue to function optimally. But after periods of sleep deficit, neurons begin to malfunction, visibly effecting a person’s behavior. What we can observe is slurred speech, stuttering, speaking in a monotone voice, or speaking at a slower pace than usual. Also sleep deprived test subjects have difficulties thinking of imaginative words or ideas. Instead, they tend to choose repetitious words or clichéd phrases and they can’t deliver a statement well. That’s because the frontal part of our brain (the Frontal Lobe) which is associated with creative thinking and speech, begins to malfunction. This means that even programming (which is a language) becomes more and more difficult as the time goes by. When you are sleep deprived, you can’t possibly come up with any good and original ideas, you can’t speak or write or even code properly, and what you can only do is mindless low-value work. Sleep deprived people have a more difficult time reacting well to unpredicted rapid changes, which means if someone who has hired you to do a job calls you or emails you and wants something to change or needs something else you will most likely pick an unoriginal solution. You also won’t have the speed or creative abilities to cope with making quick and logical decisions, nor you will have the ability to implement them well. What lack of sleep further impairs is one’s ability to simultaneously focus on several different related tasks (multitasking), further reducing the speed as well as the efficiency of one’s actions. Not only men have lower multitasking abilities than women, but also by being sleep deprived it’s getting even worse. Part of the frontal lobe, the prefrontal cortex, has several functions specifically coupled with it. Judgment, impulse control, attention, and visual association have all been related to this region of the cerebral cortex. Prefrontal Cortex (PFC) activity can drop as much as 11% after a person has missed sleep for only 24 hours. Which means you will be less able to handle your impulses and your emotions, you will be less able to focus and you will eventually start hallucinating when eventually sleep deprivation will stack up, possibly leading to temporary insanity. This region regenerates during the first stage of sleep, giving a person the ability to feel somewhat refreshed after only a short nap, so if you can’t possibly sleep, at least take a short nap. Sleep deprivation also depletes our brain of our “feel-good” chemicals like DOPAMINE! I really can’t over-emphasize this enough. Paul Ekman on his book Emotions Revealed emphasizes the importance of sleep and how sleep deprivation messes with how our emotions are being triggered and decrease our ability to control their expression. What follows is irritability, anger and violence. In fact, if the brain does not receive a break it will soon begin to shut down for periods of microsleep. This means that your brain will go to hibernation whenever it wants for some seconds or even minutes, leading you with gaps in consciousness. I certainly wouldn’t experiment driving like this. One of the possible side effects of a continued lack of sleep is death. Usually this is the result of the fact that the immune system is weakened without sleep. The number of white blood cells (guards) within the body decreases, as does the activity of the remaining white blood cells. Remember, please: Sleep is MORE important than eating. And eating on an empty stomach (or eating some healthy fats and a bit of milk or some slowly digestible source of protein) will lead to a HIGHER quality of sleep. Meditation also increases Melatonin levels and reduce cortisol levels, further improving the quality of your sleep. From all the above I hope you’ve really understood by now that: Tip 7: You need to transform your Health and Fitness If you want to transform your brain, your behaviors, your work, your income, your results and your whole life. 1- Remember to drink Water! I can remember so many times when my brain was fogged and I couldn’t think clearly, because I had forgotten to drink some water. You don’t need to wait for thirst to set in, in order to drink water. That’s far too late. The first symptom of dehydration is a dry mouth, and the second is the brain fog. And third is thirst. One last simple, small, but effective health tip is to just add lemon in your water. Although we think of lemons as having acids, when they metabolize in our gut, they provide alkaline pH in our blood and body. This is good. The more alkalinity in your blood and brain, the healthier, clearer, more energetic and more focused it can be. 2- Avoid Soft Drinks! They are not as soft as you may think. You may want to research about them more. But, almost all of them are messing with your brain. The ones that have sugar, after the sugar flood comes the insulin flood, which drops glucose levels of your blood lower than before, so your brain gets fogged. Not to mention all the hormone imbalances they trigger. You generally don’t want to mess with your blood sugar levels, because it messes with your clarity of thinking. The “sugar-free” ones, almost always have a sweetener called Aspartame, which is scientifically labelled as neurotoxic. It literally kills your precious brain neurons. Also, soft drinks create acidity in your bloodstream, clogging bloodcells together, and reducing the oxygenation of your organs, which apart from reduction in energy, it ages them (you) faster. Not good. Acidity also adds to your stress level, making you feeling even more energy-depleted (you don’t experience it instantly if they have caffeine inside). 3- Get up and MOVE! Start Exercising! To say that exercise does good to your brain health is a cliche. But I just want to mention WHY it’s really THAT important. Our brain is the most malleable organ in our body. Everything we do affects it in some way, but some things also improve or reduce its ability to learn more, be more, do more. In his book Spark: The Revolutionary New Science of Exercise and the Brain, John Ratey MD mentions the fascinating story of Naperville Central High School in Chicago, where everyday, the first class of the day is Physical Education. This was started as an experiment in the 1990′s, and the results are staggering. In 1999, the 8th grade-students were not only among the healthiest in the nation (3% obesity rate vs. 30% national average), but they are also some of the smartest in the world. Exercise, besides the better oxygenation of the body and brain, also releases endorphines (meaning literally endogenous morphines – our feel good chemicals) it also releases even more BDNF, which can also have a synergy effect with the fasting mentioned above. This will lead to more clarity, more focus, more productivity, and more free time. It will add years in your life, and also life in your years. As counter-intuitive as it may seem, by exercising daily, and especially first thing in the morning, you will have even more energy to spend throughout the day (if you don’t overdo it of course)… This is what daily exercise is about. When I found out about this, (it was by sheer luck), one day I was in a hurry so instead of being in the gym for 2 hours, I did a quick workout and left in half an hour. I was surging with energy afterwards for the rest of the day. It was like that day had double hours or something. After that, I experimented a bit. I did it again. Same results. And again and again. I love exercising daily till then. What exercise? It can be running (especially sprinting – for maximal HGH & BDNF release and fat-burning effect), weightlifting, or as simple as doing some push-ups and jumping jacks. Just doing some jumping jacks, clears our head and oxygenates our body, and offers an instant boost of energy. Bonus points if you pump up your jumps with some great music. You can even try Burpees, pull-ups, chin-ups, squats, and even handstands!!! :) All these don’t require any equipment at all and can be done at home, with your own bodyweight. I recently started learning how to do handstands (childish dream). It’s A.M.A.Z.I.N.G. :) I know most of you don’t exercise because you don’t have enough time. I understand, it’s really difficult with all these deadlines and projects running at the same time. But please, don’t make exercise a huge thing in your head. It doesn’t have to be complicated and big. It’s easy and simple. You don’t have to exercise daily 2 hours to get all the above brain and body benefits. If it’s intense, you can do just 15, 10 or even 5 minutes of exercise. Just remember to BEGIN, and after that, to push your limits. These are the only 2 things you need to be aware of. We all can just fall on our feet and do 1-5 pushups now and then. It will take you what? 5 seconds? maybe 10 seconds? It’s not a big deal. And the benefits will astonish you. Remember to pump up your body, in order to pump up your mind! Hope all of these helped and broadened your awareness. Because don’t forget that with better awareness, we make better decisions. And with better decisions we get better results! At least my awareness surely increased tenfold, by writing this lengthy article! Thank you for your patience and reaching through the end :) The information on this article is designed for educational purposes only. This information does not constitute medical advice and it should not be relied upon as such. We all have a creative Genius inside of us, and we all have experienced times when we have tapped into that genius, helping us in whatever problems, dillemas or questions we are facing. But how can we tap in that genius more often? How can we be more creative and resourceful? How can we find solutions to problems that seem completely unsolvable? In this era of dramatic distraction and overload of information, how can we overcome feeling overwhelmed? Many times we think we lack the resources, when in fact what we lack of is the awareness of our resourcefulness. In his (short) book “Problem Solving: 33 Ways to boost your Brain’s Natural Creative Ability!”, Theodore, after many years of extensive research on the brain and how we can improve it, is answering these questions and more, giving not just 33 ways, but also more problem solving techniques, skills, many activities and problem solving strategies that will really boost this innate ability when acted upon. They are all grounded in sciences (Neuroscience, Sociology, Biology, Psychology) and personal experiments, with many scientific references to research further.   Check it out now!   ...

Agile Newspeak

Every time and again, I go back to the “4 ways that agile is declining post” to see if it is still relevant. I don’t get disappointed. Now that I am a full time agile coach, I’m in a kind of a fix. Agile has crossed the chasm, and scrum won as we all know. So people expect and want Scrum. I usually don’t deliver on that, because scrum is not a solution, it’s a starting point. So what I do is start with some combination of scrum and kanban and try to fit a method to the organization I’m working with. This is of course a long process, with ups and downs, and leads to good results many times. Then I come to a place that already learned scrum. Ah, you say, if they already do scrum why do they need you?  Good question. Remember I was talking about agile as snake oil? Ok, it doesn’t really matter if they were actually sold on that oil, or that they felt that they didn’t need coaching any more, and once the coach was not there, they implemented it themselves. Or that the coach was trying to fit it to the current culture or organization. The fact is that they don’t do scrum by the book. Which is fine, if it works. I’m all for good results, no matter how you get them. Then why would they need a coach? There used to be a “scrum-but” idea. “We’re doing scrum, but we don’t do stand ups”, and you can replace the different “buts”.  That was a smell – it usually pointed to a conflict between scrum values and the organizational values, where the organization won. Then again, nobody who’s doing scrum successfully is doing vanilla scrum, so a smell can be just that. Sometimes, however, that’s not a scrum-but. They are doing scrum, there’s no but. In their eyes. Dig in and you’ll see:Product owners are not part of the team. In fact, in a sprint, each team works with multiple product owners. Product owners commit to the customer how many story points the team (who doesn’t know the requirements yet) can deliver The team can estimate all they want, but still need to meet what the POs promised. (If you think about it, estimation is really waste in that case). The team leader is the scrum master.  He needs to manage conflicting requirements and assign them to the different team members. So there’s not a real team, just a bunch a people who happen to have the same manager. Testers are assigned and rotated between teams. But since they are remote, and have their own managers funny things can happen, I’m sure you can imagine. Requirements are not all ready in the beginning of the sprint, so over time things get delayed to the end, and guess what kind of march the team is doing in the late stage of the sprint? It’s even planned ahead. Daily meetings are mostly done, but POs mostly skip them. Which makes sense, because they are busy filling their requirement quota. Finally, there’s also the small fact that people aren’t happy.They are doing scrum, they’ll tell you. The top management who brought trainers and coaches before to introduce scrum, don’t understand why scrum doesn’t work. This is not a scrum-but. This is 1984’s Newspeak. This is taking scrum vocabulary and assigning new meaning to it. It can only end in two ways: Giving another chance to scrum, with coaches, and trainers, and management backing. Or they can just proclaim that “scrum is snake oil” and wait for the new hot thing.Reference: Agile Newspeak from our JCG partner Gil Zilberfeld at the Geek Out of Water blog....

WildFly 8.2.0.Final release – Quick overview of the changes

It’s been a while since I last wrote on this blog. Although I have had some topics that I wanted to blog about, I just haven’t found enough time to do it. I finally decided to write this up today after I saw a mail from one of the JBoss community members, checking up on why there haven’t been any updates here lately (thanks for checking, Bhaskar!). Before I move on to some technical things, a quick personal update – It’s now been more than a year now since I changed jobs. I no longer work at Red Hat, JBoss. My (almost) 5 years at JBoss have been very fruitful and I enjoyed being part of the (JBoss AS/WildFly) application server development team. Last year, I decided to move on to something different and the right opportunity came along and I decided to take it up. Some of you know that I’ve been involved with the JBoss community for longer than the 5 years that I had been employed at Red Hat. I have been a JBoss community member since around 2004/2005, so even though I have moved on from Red Hat, I am still active in the JBoss forums. Now that you all know what I’ve been upto, let’s move on to some technical things. WildFly 8.2.0.Final released! The WildFly team just released the 8.2.0.Final version of WildFly some days back. As usual, it’s available for download on the project’s download page http://wildfly.org/downloads/. This is mainly a bug fix (plus some features) release in the 8.x series. I for one, was pleased to see this release happen because it allows the community to receive bug fixes on top of 8.1.0.Final release, which has been tested/used in the community for quite some time now. The WildFly team has indicated that this will be the last release in the 8.x series which sounds reasonable, given that the development team has already moved on to work on the 9.x series. It’s never easy to work/maintain more than one major version of the code, especially in the context of bug fixes and backward compatibility. What does WildFly 8.2.0.Final contain? The complete overview of changes in available in this announcement on Jason’s blog http://wildfly.org/news/2014/11/20/WildFly82-Final-Released/. CDI spec upgrade and improved WebSocket support are the main items in terms of feature set. There’s also this note in the release notes:– EJBs in WARs now inherit the WAR security domainThere was a recent forum thread, where one of the users asked what that really means. Here’s some background to that change https://issues.jboss.org/browse/WFLY-3102. As noted in that JIRA, this was feature request that was raised in the context of EJBs packaged in .war deployments. Most of you, I guess, will be aware that Java EE spec allows EJBs to be deployed as part of the .war deployment. What this means is that you can place your EJB classes within the .war/WEB-INF/classes or within a jar in .war/WEB-INF/lib. Although, this sounds straightforward for the end users, there are some technical implications to this (given the way Java EE “components” and “modules” are defined and configured within the server ecosystem). One such detail, is the way one configures the EJBs that are part of the .war deployment. Remember that if this EJB was part of a separate EJB module (within a .jar packaging outside of the .war) then one would use the ejb-jar.xml (and the WildFly specific jboss-ejb3.xml) as the deployment descriptors to configure it. This applies to EJBs deployed in a .war deployment too. i.e. one can use those same files for configuring EJBs. Now since these EJBs are part of a .war, the .war itself can/will have a deployment descriptor if its own (the web.xml and jboss-web.xml). With that context, consider a case where the you have EJBs within the .war deployment and your .war deployment descriptor (the jboss-web.xml) configures a specific security domain for that deployment. Now remember that the EJBs too can configure a security domain (in jboss-ejb3.xml) and if none is configured and security is enabled on some EJBs, then the default “other” security domain gets used. So let’s say your .war deployment, in which the EJBs reside, states that it wants to use “foo-bar” security domain and the EJBs, within that deployment, don’t specify any specific security domain. So what should one expect in such scenario? Should the EJBs use the security domain configured at the .war level or should they default to the “other” security domain (since the EJB deployment descriptors don’t specify any specific security domain configuration). The previous versions of WildFly had decided to use the default “other” security domain for the EJBs in such a case. Of course, the EJBs could use a jboss-ejb3.xml to set a different security domain, one which matches the jboss-web.xml. So that JIRA which I linked to earlier requested for a better, smarter and a more logical default in such cases. So starting this 8.2.0.Final version of WildFly, if you have a .war containing the EJBs and the EJBs don’t define a security domain, then the security domain for any secured EJBs in that deployment *defaults* to the one that’s defined at the .war deployment level. If the .war deployment doesn’t set any specific security domain, then it ultimately, defaults to the “other” security domain. A good and logical change IMO. This will reduce some of the “surprises” that users have reported with previous version of WildFly, when it came to the security domain usage of EJBs in .war deployments. For more about this, you can read the discussion here https://developer.jboss.org/thread/250375 and ask any questions you have around this, in that thread. What are the other notable things in WildFly 8.2.0.Final? Although, not specific to 8.2.0.Final, the WildFly release contain a “patch” distribution which you can use if you already are using WildFly 8.1.0.Final and just want to “upgrade” to this new release. WildFly 8 has patch management built in and one can apply this patch on top of an existing 8.1.0.Final version. What’s next for WildFly? As noted earlier, the WildFly development team has moved on to the next version of the project. Work is now continuing on 9.x version which already has a Alpha version released. So going forward, from what I have read, the releases will happen in the 9.x series.Reference: WildFly 8.2.0.Final release – Quick overview of the changes from our JCG partner Jaikiran Pai at the Jaikiran My Wiki blog....

15 Tools Java Developers Should Use After a Major Release

The ultimate survival kit for new deployments Unlike toying around with zombie apocalypse scenarios, debating the machete versus the shotgun, troubles in Java production environments are quite real, especially after new deployments (but it’s good to be ready for zombies as well). Taking this a step further, it’s much easier to get into trouble today than ever before when new code shipping cycles are cut down to weeks and sometimes days or even multiple times a day. To avoid being run down by the zombies, here’s the survival kit setup you need to fully understand the impact of new code on your system. Did anything break? Is it slowing you down? And how to fix it? Here’s the tool set and architecture to crack it once and for all. Logging Other than shrinking release cycles, another property of the modern development lifecycle is ever expanding log files that can reach GBs per day. Let’s say some issue arises after a new deployment: If you’d like to produce a timely response, dealing with GBs of unstructured data from multiple sources and machines is close to impossible without the proper tooling. In this space we can essentially divide the tools to the heavy duty enterprise on-premise Splunk, and its SaaS competitors like Sumo Logic, Loggly and others. There are many choices available with a similar offering so we wrote a more in-depth analysis of log management that you can read right here. Takeaway #1: Set up a sound log management strategy to help you see beyond the pale lines of bare logfiles and react fast after new deployments. One logging architecture we’ve found to be super useful after deploying new code is the open-source ELK stack. It’s also worth mentioning since it’s open-source and free.    So what is this ELK we’re talking about? A combination of elasticsearch’s search and analytics capabilities, Logstash as the logs aggregator and Kibana for the fancy dashboard visualization. We’ve been using it for a while, feeding it from Java through our logs and Redis, and it’s in use both by developers and for BI. Today, elasticsearch is pretty much built-in with Logstash, and Kibana is an elasticsearch product as well, making integration and setup go easy peasy. When a new deployment rolls out, the dashboards follow custom indicators that we’ve set up about our apps health. These indicators update in real time, allowing close monitoring when freshly delivered code takes its first steps after being uploaded to production. Takeaway #2: Search, visualization and the ease of aggregating logs from multiple sources are key factors in determining your log management strategy. Takeaway #3: From a developer perspective, evaluating the impact of a new deployment can include BI aspects as well. Tools to check:On-premise: Splunk SaaS: Sumo Logic SaaS: Loggly Open source: Graylog2 Open source: Fluentd The ELK stack (Open source): Elasticsearch + Logstash + Kibana Performance Monitoring So the release cycles are cutting down and log files are becoming larger, but that’s not all: The number of user requests grows exponentially and they all expect peak performance. Unless you work hard on optimizing it, simple logging will only take you this far. With that said, dedicated Application Performance Management tools are no longer considered to be a luxury and rapidly become a standard. At its essence, APM means timing how long it takes to execute different areas in the code and complete transactions – this is done either by instrumenting the code, monitoring logs, or including network / hardware metrics. Both at your backend and on the users’ devices. The first two modern APM tools that come to mind are New Relic, who just recently filed their IPO, and AppDynamics.  Each traditionally targeted a different type of developer, from enterprises to startups. But as both are stepping forward to their IPOs and after experiencing huge growth the lines are getting blurred. The choice is not clear, but you could not go wrong – On premise = AppDynamics, otherwise, it’s an individual call depends on which better fits your stack (and which of all the features they offer are you actually thinking you’re going to use). Check out the analysis we recently released that compares these two head to head right here. Two additional interesting tools that were recently released are Ruxit (by Compuware) and DripStat (by Chronon Systems), each coming from larger companies with their own attempt to address the SaaS monitoring market pioneered by New Relic. Looking into hardcore JVM internals, jClarity and Plumbr are definitely worth checking out as well. Takeaway #4: New deployments may affect your application’s performance and slow it down, APM tools can provide an all around overview of your applications health. Tools to check: AppDynamicsNew Relic New players: jClarityPlumbrRuxitDripstat Debugging in Production Release cycles are down, log files grow large, user requests explode, and… the margin for error simply doesn’t exist. When an error does come – you need to be able to solve it right away. Large-scale production environments can produce millions of errors a day from hundreds of different locations in the code. While some errors may be trivial, others break critical application features and affect end-users without you knowing it. Traditionally, to identify and solve these errors you’d have to rely on your log files or a log management tool to even know an error occurred, let alone how to fix it. With Takipi, you’re able to know which errors pose the highest risk and should be prioritized, and receive actionable information on how to fix each error.Looking at errors arising after new deployments, Takipi addresses 3 major concerns:Know which errors affect you the most – Detect 100% of code errors in production, including JVM exceptions and log errors. Use smart filtering to cut through the noise and focus on the most important errors. Over 90% of Takipi users report finding at least one critical bug in production during their first day of use. Spend less time and energy debugging – Takipi automatically reproduces each error and displays the code and variables that led to it – even across servers. This eliminates the need to manually reproduce errors, saves engineering time, and dramatically reduces time to resolution. Deploying without risk – Takipi notifies you when errors are introduced by a new version, and when fixed errors come back to haunt you.Takeaway #5: With Takipi you’re able to act quickly to resolve any issue and no longer in the dark after a new release. Tools to check: TakipiAlerting and tracking Release cycles, log files, user requests, no margin for error and… how you’re going to follow up on it all? You might think this category overlaps with the other’s and the truth is that you’re probably right, BUT when all of these tools have their own pipelines for letting you know what went wrong – It gets quite cluttered. Especially in the soft spot after a new deployment when all kinds of unexpected things are prone to happen (which are gentler words for… all hell breaks loose). One of the leading incident management tools that tackles this is PagerDuty: Collecting alerts from your monitoring tools, creating schedules to coordinate your team and deliver each alert to the right person through texts, emails, sms or push notifications. Takeaway #6: Consider using an incident management system to handle information overload. A specialized tool we really like using here is Pingdom (which also integrates with Pagerduty). What it does is quite simple and just works: Tracking and alerting on our website’s response times 24/7. Answering a crucial question that seems trivial: Is the website available? Probing it from different locations all over the globe.  Another angle to tackle information overload is error tracking that goes beyond the features of log analyzers: Smart dashboards to manage your exceptions and log errors. Aggregating data from all your servers and machines to one single place, either through your log events or other plugs coming from your code. For a deeper dive to the error tracking tools landscape, check out this post that covers the most popular options. Takeaway #7: Code errors come in all shapes and sizes, it’s worth giving them some special treatment with an error tracking tool (and smash some bugs while we’re at it, muhaha). Tools to check: PagerDutyPingdomConclusion We’ve experienced first hand how modern software development affects the release lifecycle and zoomed in on how you can assess the impact of new rapid deployments – when new code can come in before you even fully understood the last update’s impact. In the grand scheme of things, any tool you consider should address these 5 characteristics:Shrinking release cycles Expanding log files Growing user requests Smaller margins for error Information overloadMost importantly, think of how you’re handling these today and which takes up too much of your time. Chances are that there’s a tool to solve it.Reference: 15 Tools Java Developers Should Use After a Major Release from our JCG partner Alex Zhitnitsky at the Takipi blog....

Java SE 8 new features tour: Traversing, filtering, processing collection, & methods enhancements with Lambda

In this article of the “Java SE 8 new features tour” series, we will deep dig into explanation, and exploring the code, on how to traverse the collections using lambda expression and with method references, filtering them with predicate interface, implementing default methods in interfaces, and finally implementing static methods in interfaces. In the previous article “Functional programming with Lambda Expression”; I have deeply dived into understanding lambda expressions. I have shown you a few different uses of Lambda Expressions. They all have in common the implementation of functional interfaces. I have also explained how the compiler is inferring information from code, such as specific types of variables and what is really happening in the background. Source code is hosted on my Github account: Clone it from here. Table of Content:Traversing collections with lambda expressions. Filtering collections with predicate interfaces. Traversing collections with method references. Implementing default methods in interfaces. Implementing static methods in interfaces.1.Traversing collections with lambda expressions In Java SE 8, you can use lambda expressions to traverse a collection of items. Examples of collections include lists, maps, and sets. All of these data types implement an interface called iterable. To understand the code I’m about to show you, let’s start in the documentation. I’m working a class called TraverseFileContent.java under eg.com.tm.java8.features.lambda2 package. I’ll right click into the method name readAllLines and then Show Javadoc. It returns List class that extends a number of interfaces. This is the one I’m interested in called iterable. This interface was added in Java SE 5. And it has a method called iterater. That returns an instance of an Iterater interface that you can use then to loop through the contents of a collection. But in Java SE 8 there were a couple of new methods. One called forEach, and one called spliterator. I’m going to focus on the forEach method. It accepts an instance of a functional interface, called Consumer. The consumer interface has a single abstract method, named accept. And by implementing this interface and its single abstract method, you can add code that operates on an item in the collection. So, let’s go back to the code. In the TraverseFileContent.java class, I’m traversing this lines collection, this array list of strings representing the contents of a file, twice. In first version, starting at line 51, I’m using a forEach loop, it’s a simple bit of code, and it creates a line String variable for each item in the list and then executes whatever code is needed. At line 58, I’m using another approach, calling the iterator method of the collection. Getting an iterator object and then looping with a while code block, calling the iterators has next method. Now both of these bits of code have worked fine going all the way back to Java 5, but I’ll show you what this might look like with a lambda expression and the forEach method. In Java 8, I’ll start with this forEach method. Starting at line 65 I’ll reference my lines collection and call the new forEach method. And again it’s going to receive an instance of the Consumer interface. Because Consumer is a functional interface, I can use a lambda expression. The Consumer interface’s accept method requires a single argument of the appropriate data type. Because lines variable is declared as a list of strings, I have to pass in a string as the argument. I’ll pass it in with a name of line. Then I’ll add my lambda operator, the arrow token. And I’ll add my system output here, and pass in line. And you can clean up the code a bit by removing old traversals. And now this single line of code replaces the three lines of the forEach loop. I’ll make a copy of this code and move down here to the version that’s using an iterater. And I’ll select those lines of code and comment them out. And paste in my lambda expression version. So when you replace an iterator, you’re replacing four lines of code with a single line. More advanced you can use Stream with collections, Streams supports a sequence of elements supporting sequential and parallel aggregate operations. Normally it is used as the following: Now save and run the code and see that it behaves exactly the same as it did before, but just with less code. So this is just another option for traversing collections. You can use forEach loops. You can use iterator objects and now you can use the forEach method with a lambda expression. 2.Filtering collections with predicate interfaces In addition to the new lambda syntax, Java SE 8 adds a number of new functional interfaces. One of the most useful is called the Predicate Interface. An interface that has a single boolean method named test, which you can use to wrap up your conditional processing, and make conditional code a lot cleaner. I’ll show you how to use the predicate interface in this project. Starting in the class named FileDirFilter class in package eg.com.tm.java8.features.lambda2.predicate, I’ve declared a method called predicateInInnerClass. I will use NIO.2 DirectoryStream class, to get a specific path entries stream, which in our case is declared as: Now my goal is to filter this stream and only display certain entries, which are directories. You can use the predicate interface either with inner class syntax or with lambda syntax. I’ll start with inner class syntax. In predicateInInnerClass method, I’ll declare an instance of the predicate interface. I’ll type the name of the interface and press Ctrl+Space. And choose the interface from the list. It’s a member of the package Java.util.function, and you’ll find a lot of other new functional interfaces there as well. This interface needs a generic type declaration. I’ll set that to the name Path class. And I’ll name the predicate, dirsFilter. Now, for inner class syntax, I’ll start with the new keyword, and I’ll press Ctrl+Space and choose the constructor for the predicate interface. When I choose that, NetBeans automatically implements the single abstract method, test. Because I declared my predicate with a generic type of Path, the test method accepts a single argument of that type as well. Now, I’m going to implement the method. I’m going to change the name of the path object being passed in to just “t”. I’ll set the return statement to use a very simple criteria. I’ll add a set of parentheses to wrap my condition. And I’ll set the condition to isDirectory(t, NOFOLLOW_LINKS). So now my predicate object encapsulates my test, and the test method can be used to determine whether I want to process an object from my collection. The next step is to traverse the collection. And you can do this in a number of ways with a forEach loop, an iterator object, or with the new forEach method. I’ll use the classic forEach loop. I’ll type foreach and press Ctrl+Space, and choose the foreach code template. Within the for loop, I’ll use an if statement. And I’ll set the condition to use the dirsFilter object that I just declared. I’ll call dirsFilter.test. I’ll pass in the file object that I’m declaring in foreach loop. And then if the condition is true, I’ll use system output and I’ll output the results of calling the getFileName method of the file object. I’ll save and run that code. And I only see full path of paths of type directory. Now, if I want to change my condition, I can change the predicate object and rerun the code and it’ll work fine. But our goal here is to make the code as concise and readable as possible. And for that, you might decide instead to use a lambda expression to implement this predicate interface. So let’s go back to the code, and I’ll fold this method, predicateInInnerClass, and unfold other method, predicateWithLambda. Now I’m going to do very similar processing. But I’ll declare my predicate object this time using a lambda expression. Once again, I’ll type the name of the interface. I’ll press Ctrl+Space and choose it from the list, and set its generic type. And I’ll name this predicate object noFilter. Now I’ll implement the interface using a lambda expression. I’ll start with the signature of the method I’m implementing. That’s the test method. And because I declared predicate with a generic type of Path, the argument is going to be an instance of path. I’ll just name it p. Then I’ll add the arrow token, and then I’ll implement my method with a simple conditional expression, to true to just return all defined path entries. And that’s all I need. This single line of code replaced five or six lines of code in the inner class version. Next, I’ll loop through the list and use the test method of the predicate object. This time, I’ll use the doFilterAndPrintPath method passing in my predicate noFilter. I showed how to use this method in previous lambda implementations. It’s a new method that was added in Java SE 8. In implementation of doFilterAndPrintPath method I am using the forEach method of newDirectoryStream returned collection of paths, I’ll start with the name of the object I’m passing in as an argument. This time I won’t wrap it inside parentheses just to show you a difference in syntax. Then I’ll add the arrow token and a pair of braces. Within the braces I’ll use an if statement. And I’ll pass in my condition, which again the predicate’s test method. I’ll use pred.test, and I’ll pass in the path object. And if the condition is true, I’ll use system output. And I’ll output the path object file name. I’ll save and run the code. And there is the result. Once again, I’m displaying all entries. But what if I want to deal with more than one possible condition? Well this is the great thing about lambda syntax and the predicate interface. You can make as many predicate objects, as you want, each representing a different condition. So I’m going to duplicate this line of code, and I’ll change the name of the new one to hiddenFilter. And I’ll change its condition to show only hidden files and directories. To make it really easy to pass in whichever predicate I want, I’ll take this code that’s traversing the collection, and put it into its own separate method. We already did that in doFilterAndPrintPath method. Now, the method doesn’t know which predicate it’s going to get, so I’m refactored the name of the predicate object in the method to just pred. And now, my existing code is passing in hiddenFilter, so I’ll run that. And I get all hidden files and directories. And then I’ll change the predicate object that I’m passing in to timeFilter, and I’ll run the code again. And this time I get all files and directories that is modified today. So this is how you can use the new predicate interface and lambda expressions to encapsulate your conditions in individual objects. And then pass those objects into your own methods for processing. I won’t cover a lot of the other new functional interfaces in Java SE 8 in detail, but I encourage you to investigate the package that the predicate interface is a part of java.util.function. You’ll find a lot of new useful interfaces there. And because they’re all functional interfaces, they can all be implemented with lambda expressions. 3.Traversing collections with method references In addition to Lambda expressions, Java SE 8’s Project Lambda also adds method references to the language. A method reference gives you a way of naming a method you want to call, instead of calling it directly. And just like Lambda expressions, the goal is to make your code more concise and more readable. I’ll demonstrate this in this class named MethodReference under package eg.com.tm.java8.features.lambda2.mthdRefs. You can use method references on four kinds of methods:Static methods of any class. Instance methods of a particular object. Instance methods of an arbitrary object, in which case you would refer to it just like it was a static method. And references to constructor methods.I’ll start with static methods. In this code, I have a FilesDirTests class, and my goal is to check wither a specific file is accessible or not. I’m going to create a method that does some comparisons to a path class. Now you could put this method anywhere you like, and developers will differ about the best place to put it, but I’m going to create the method as a static method of my FilesDirTests class. I’ll open the class and I’ll place this new method. I’ll declare it as public and static, and set its return data type to boolean. I’ll name the method isAccessible. And the method will accept reference to path class. I’ll name it p. This method will know that the goal is to compare path against some accessibility methods defined in java.nio.file.Files class. And just like the test method of the Predicate interface, this will return a true if the path is accessible, or false to indicate that path is not accessible. I’ll save that change, and now I’ll go to my class MethodReference. To test accessibility of a given path files, I once again use the doFilterAndPrintPath(Predicate<Path> pred) method. I’ll call it inside doPrint method. The defined path is used inside doFilterAndPrintPath method. And for the predicate object, I’ll use a method reference. It’ll look like this, I’m referring to a static method, and so I’ll start with the type, the class that contains the static method. Then I’ll put in the double colon operator, that’s how you separate the type or the object from the name of the method that you’re calling. And then I’ll pass in the name of the method, isAccessible. Now here’s why this is working. This method, the doFilterAndPrintPath method, is expecting an instance of the predicate interface. That interface has a single abstract method, which expects one value. I’m calling a method that expects one value. And returning a data type that can be used by the test method. The doFilterAndPrintPath will traverse the path files, and output the values according to the test. Save the change, and run the code, and there’s the result. Opppps There is no result? No files printed? This is because isAccessible has test condition that will make the test fails, which is isExecutable method. So that’s a static method reference. If you prefer, you can use method references with instance methods. To do this, I’m going to go down at the end of MethodReference class and add the following two methods: In this class, in the main method, I’m creating an instance of the current class, and then calling it doFilterAndPrintPath method. By the time I get down here, all of the data and the methods are instance members, rather than static members. Because main is a static method, so we can’t use this keyword, as alternative syntax you can use this keyword as reference inside object instance methods. And just as I did before, I’ll save and run, and there’s the result. So method references are a simple way of making your code incredibly concise. 4.Implementing default methods in interfaces Prior to Java SE 8, interfaces could contain abstract methods and constant declarations, but you couldn’t provide fully implemented methods that would be inheritable. I’m working in a package called eg.com.tm.java8.features.lambda2.defltMthd. And in this application, I have an interface named VehicleInterface.Java. It has eight abstract methods, in interfaces all abstract methods are soon to be public, so I haven’t included the public keyword and these are basic getters and setters. Then I’ve a class named Car.java and this class has the setters and the getters implemented. And a constructor method that makes it easy to instantiate the class. And then I have a main class called DefaultMethod.java. In this code, I’m filtering a list of cars using a predicate object, and then, display cars. I’m putting together a string named info and outputting it to the console. So, I’m going to refactor this code using a new capability of Java SE 8 that lets me add something called a default method to an interface. When you add a default method to an interface, you can add its full implementation. And then, any class that implements that interface will inherit that method and you can call it itself or the method will be callable from anywhere else in the application because, just like the abstract methods, it will be public. Back to VehicleInterface.Java I’ll move the cursor below the abstract methods. And I’ll start my method signature with the new keyword, default. The rest of the method will look exactly the same, as if I were implementing it in a class. I’ll start with the return type, then the name of the method. Next, I’ll add the code, and it’ll be a return statement that can concatenate the values of the name, model, car CC and the make year. Now, because this is an interface, I can’t refer to private fields. You can’t do that. So, I’m just going to refer to the abstract methods, which I know will be implemented by the class itself. I’ll call getName, getModel, getCC. Then I’ll concatenate getMakeYear and a closing parenthesis. I’ll save that change and now that method is available to every class that implements the interface. I won’t make any changes to the Car class. It already has that method. Then I’ll go over here to my main class, use default method, and I’ll change this code. I no longer need to create the string named Info, that’s going to be done by the new method that the Car class has inherited. So, I’ll comment out that line of code. And I’ll replace the reference to the info variable with a call to the getInfo method. But I’ll call it as a member of the car object that I’m working with right now. I’ll save the change and run the code. And there’s the result. I’m successfully calling the getInfo method to get a string, a concatenation of the values of the name, model, CC and make year, and then I’m outputting it to the console using the code in my main class. By using default methods, you can sometimes eliminate a whole layer of inheritance. Some developers, for example, in earlier versions of Java, might have created an interface, then a base class that implemented the interface and then a subclass that they would actually use in their code. With this new capability, you might not need the base class at all and instead, can go directly to implementing the subclasses, inheriting the default methods directly from the interfaces. 5.Implementing static methods in interfaces I previously described how to add default methods to interfaces, which are fully implemented and are inherited by implementing classes. In Java SE 8, you can also add fully implemented static methods to interfaces. Just as with default methods, the goal is to let you eliminate inheritance layers and simplify your applications. I’m working in a package called eg.com.tm.java8.features.lambda2.staticMthd. Just as in the earlier project, the one for default methods, the main class, which is called StaticMethod here, has code that gets the name, model, CC and make year from a car object. It’s at line 47 in this class. My goal is to take this code and move it to a static method, but instead of adding it to a base class or other concrete class, I’m going to add it to an interface. Something I wasn’t able to do in earlier versions of Java. I’ll take this code and copy it to the clipboard. Then, I’ll open the interface, named VehicleInterface.java. Just as before, I’m starting with a set of abstract method declarations. Now, I’ll place the cursor after those abstract method declarations and I’ll start with the keyword static. Just as with the default method and the abstract methods, this will be a public method automatically. I don’t need to declare it. It’ll return a string and I’ll name it getVehicleInfo. Now because this is a static method, it can’t refer to the instance methods declared above. So, I’m going to pass in an instance of the Car object. Then I’ll provide the return keyword and I’ll paste in the code from before and I’ll clean this up so that now I’m returning the name, model, CC and make year and the closing parenthesis. Now this static method is available from anywhere in the application. Just as before, I don’t need to do anything to my Model class. That’s called car, because all the code that’s going to be getting the string and outputting it, is already available in the interface. I’ll go back to my main class, use static method, and now, instead of putting together this string here, I’ll call the interface using the interface’s name, VehicleInterface.java, then I’ll call the new static method, getVehicleInfo and pass in the Car object, which is c. And I’ll save the change and run the code. And there’s the result. Functionally, it’s exactly the same as using a default method, or putting this code into the Car class, or having it right here at the top level in the main class. The goal of both default and static methods is just to give you more options in putting together the inheritance model for your application. Using both default and static methods, you can eliminate entire inheritance layers of your application and enormously simplify the coding model, making the application easier to code and to maintain. ResourcesThe Java Tutorials, Lambda Expressions JSR 310: Date and Time API JSR 337: Java SE 8 Release Contents OpenJDK website Java Platform, Standard Edition 8, API SpecificationReference: Java SE 8 new features tour: Traversing, filtering, processing collection, & methods enhancements with Lambda from our JCG partner Mohamed Taman at the Improve your life Through Science and Art blog....

Arquillian Cube. Let’s zap ALL these bugs, even the infrastructure ones.

Docker is becoming the de-facto project for deploying applications inside lightweight software containers in isolation. Because they are really lightweight they are perfect not only to use in production, but to be used inside developer/qa/CI machine. So the natural step is start writing tests of your software that runs against these containers. In fact if you are running Docker on production, you can start writing infrastructure tests and run them as a process of your release chain (even debugging in developer machine) before touching production. That’s pretty cool but you need a way to automate all these steps from the point of view of developer. It should be amazing if we could startup Docker containers, deploy there the project and execute the tests from a JUnit and as easy as a simple JUnit. And this is what Arquillian Cube does. Arquillian Cube is an Arquillian extension that can be used to manager Docker containers from Arquillian. Extension is named Cube for two reasons:Because Docker is like a cube Because Borg starship is named cube and well because we are moving tests close to production we can say that “any resistance is futile, bugs will be assimilated”.With this extension you can start a Docker container with a server installed, deploy the required deployable file within it and execute Arquillian tests. The key point here is that if Docker is used as deployable platform in production, your tests are executed in a the same container as it will be in production, so your tests are even more real than before. But also let you start a container with every required service like database, mail server, … and instead of stubbing or using fake objects your tests can use real servers. Let’s see a really simple example which shows you how powerful and easy to use Arquillian Cube is. Keep in mind that this extension can be used along with other Arquillian extensions like Arquillian Drone/Graphene to run functional tests. Arquillian Cube relies on docker-java API. To use Arquillian Cube you need a Docker daemon running on a computer (it can be local or not), but probably it will be at local. By default Docker server is using UNIX sockets for communication with the Docker client, however docker-java client uses TCP/IP to connect to the Docker server, so you will need to make sure that your Docker server is listening on TCP port. To allow Docker server to use TCP add the following line to /etc/default/docker: DOCKER_OPTS=”-H tcp:// -H unix:///var/run/docker.sock” After restarting the Docker daemon you need to make sure that Docker is up and listening on TCP. $ docker -H tcp:// version Client version: 0.8.0 Go version (client): go1.2 Git commit (client): cc3a8c8 Server version: 1.2.0 Git commit (server): fa7b24f Go version (server): go1.3.1 If you cannot see the client and server versions then means that something is wrong in Docker installation. After having a Docker server installed we can start using Arquillian Cube. In this case we are going to use a Docker image with an Apache Tomcat and we are going to test a Servlet. @WebServlet("/HelloWorld") public class HelloWorldServlet extends HttpServlet {@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); writer.println("Hello World"); } } And the test: @RunWith(Arquillian.class) public class HelloWorldServletTest {@Deployment(testable=false) public static WebArchive create() { return ShrinkWrap.create(WebArchive.class, "hello.war").addClass(HelloWorldServlet.class); }@Test public void should_parse_and_load_configuration_file(@ArquillianResource URL resource) throws IOException {URL obj = new URL(resource, "HelloWorld"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET");BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer();while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close();assertThat(response.toString(), is("Hello World")); } } Notice that the test looks like any other Arquillian test. Next step is add Arquillian dependencies as described in http://arquillian.org/guides/getting_started and add arquillian-cube-docker dependency: <dependency> <groupId>org.arquillian.cube</groupId> <artifactId>arquillian-cube-docker</artifactId> <version>1.0.0.Alpha1</version> <scope>test</scope> </dependency> Because we are using Tomcat and because it is being executed in a remote host (in fact this is true because Tomcat is running inside Docker which is external to Arquillian), we need to add Tomcat remote adapter. <dependency> <groupId>org.jboss.arquillian.container</groupId> <artifactId>arquillian-tomcat-remote-7</artifactId> <version>1.0.0.CR7</version> <scope>test</scope> </dependency> And finally arquillian.xml is configured: <?xml version="1.0"?> <arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jboss.org/schema/arquillian" xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd"><extension qualifier="docker"> (1) <property name="serverVersion">1.12</property> (2) <property name="serverUri">http://localhost:2375</property> (3) <property name="dockerContainers"> (4) tomcat: image: tutum/tomcat:7.0 exposedPorts: [8089/tcp] await: strategy: polling env: [TOMCAT_PASS=mypass, JAVA_OPTS=-Dcom.sun.management.jmxremote.port=8089 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false] portBindings: - exposedPort: 8089/tcp port: 8089- exposedPort: 8080/tcp port: 8080 </property> </extension><container qualifier="tomcat" default="true"> (5) <configuration> <property name="host">localhost</property> (6) <property name="httpPort">8080</property> (7) <property name="user">admin</property> (8) <property name="pass">mypass</property> </configuration> </container></arquillian> (1) Arquillian Cube extension is registered. (2) Docker server version is required. (3) Docker server URI is required. In case you are using a remote Docker host or Boot2Docker here you need to set the remote host ip, but in this case Docker server is on same machine. (4) A Docker container contains a lot of parameters that can be configured. To avoid having to create one XML property for each one, a YAML content can be embedded directly as property. (5) Configuration of Tomcat remote adapter. Cube will start the Docker container when it is ran in the same context as an Arquillian container with the same name. (6) Host can be localhost because there is a port forwarding between container and Docker server. (7) Port is exposed as well. (8) User and password are required to deploy the war file to remote Tomcat. And that’s all. Now you can run your test and you will see how tutum/tomcat:7.0 image is downloaded and started. Then test is executed and finally the docker container is stopped. This has been a simple example, but you can do a lot of more things like creating images from Dockerfile, orchestrate several docker images or enrich the test to programmatically manipulate containers. For more information you can read https://github.com/arquillian/arquillian-cube and of course any feedback will be more than welcomed.Reference: Arquillian Cube. Let’s zap ALL these bugs, even the infrastructure ones. from our JCG partner Alex Soto at the One Jar To Rule Them All blog....

SWT Mouse Click Implementation

Doing a bit of SWT custom widget development lately, I stumbled across the question why is there no such thing as a default SWT mouse click listener? As this subject raises once in a while, I thought writing a word or two about the rational ground behind – and how to implement mouse clicks in general – would not hurt. SWT Mouse Click Event driven widget toolkits usually distinguish between low-level and semantic events. A low-level event represents window system occurrences or low level input. The mouse and keyboard inputs belong basically to this group. Semantic events in turn are the result of control specific user interaction and might be composed of one or more low-level events. A button-click for example could be specified as a mouse-down followed by a mouse-up without the mouse leaving the bounds of the control. The point of the matter is the control specific user interaction. An image-click might be specified as a mouse-down followed by a mouse-up without leaving the bounds of particular regions of the image. Which makes a small but mighty difference. The semantic event type SWT.Selection e.g. corresponds to the button-click specification given above for the org.eclipse.swt.widgets.Button control. But its composition is quite different on org.eclipse.swt.widgets.Slider. The latter behaves rather like the image-click definition:It is obvious that nobody would like to add particular listeners for mouse-click events on each of the control’s regions. It is much more comfortable to have a semantic abstraction based on those low-level events that notifies observers about the crucial point or interest1. Button Click for Custom Widgets So how can a button-click event implementation look like on a (sub-)component of a custom SWT widget? Consider for example a Composite comprised of a few labels and one of those – for whatever reason – should serve as an action trigger. The click behavior could be accomplished with a little action wrapper working on top of the typed event abstraction of SWT. It may implement/extend org.eclipse.swt.events.MouseListener/-MouseAdapter and can be registered at controls to serve as a button-click listener: static class ClickBehavior extends MouseAdapter {private final Runnable action;ClickBehavior( Runnable action ) { this.action = action; }@Override public void mouseDown( MouseEvent event ) { // TODO: decent implementation }@Override public void mouseUp( MouseEvent event ) { // TODO: decent implementation } } As you can see the class ClickBehavior wraps a Runnable which should be triggered by a click on the observed control. To do so the first step is to verify that a left-mouse-button-down has occured and flag the observer to be trigger ready. A simple mouseDown implementation might look like this: public static final int LEFT_BUTTON = 1; [...] public void mouseDown( MouseEvent event ) { if( event.button == LEFT_BUTTON ) { armed = true; } } The second step is to check whether a subsequent mouseUp event has occured within the bounds of the monitored control. If so (and armed) the semantic condition has been fulfilled and the action can be triggered 2: public void mouseUp( MouseEvent event ) { if( armed && inRange( event ) ) { action.run(); } armed = false; }static boolean inRange( MouseEvent event ) { Point size = ( ( Control )event.widget ).getSize(); return event.x >= 0 && event.x <= size.x && event.y >= 0 && event.y <= size.y; } This implementation is sufficient to be able to handle a ‘button-click’ event on e.g. a org.eclipse.widgets.Label as shown by the following snippet: final Shell shell = [...]; Label label = new Label( shell, SWT.NONE ); label.setText( "Click me!" ); label.addMouseListener( new ClickBehavior( new Runnable() {@Override public void run() { MessageBox box = new MessageBox( shell ); box.setMessage( "Label was clicked." ); box.setText( "Message" ); box.open(); }} ) ); And voilà, this is how it looks like at runtime:Wrap Up As explained above there are good reasons for SWT to omit a general purpose mouse click implementation. And the given example showed how to implement a simple button-click semantic for custom widgets. However there is still more to consider. Widgets often react on mouse down visually to indicate that they are trigger-ready for example. Because of this custom widget code gets quickly blown up and tend to blur the various event related reponsibilities. For a clean separation of the event-semantic from the visual-effect code, I usually extract the first one in a little helper class. I even have a general purpose version for button-click events called ButtonClick, which is part of the SWT utility feature of the Xiliary P2 repository. In case all this mouse click related content raised a desire for some practical application of mouse clicking: how about using the social buttons below to share the knowledge?  The attentive reader may have recognized that I omit the slider’s drag region which also adds to the selection semantic. This is because it does not match the click behaviour and would go beyond the scope of this discussion. ↩ It might be noteworthy to mention that a real world implementation should ensure that the armed flag gets also reset in case a runtime exception is thrown during action.run(). ↩Reference: SWT Mouse Click Implementation from our JCG partner Frank Appel at the Code Affine blog....

Scala snippets 2: List symbol magic

The following other snippets are also available:Scala snippets 1: FoldingIn scala every symbol can be a function, so overloading operators (which isn’t really overloading, since operators are already methods) is very easy and is something which you see in many libraries. In this snippet we’ll just explore a couple of the overloaded methods that make working with lists much easiers. So lets get started and look at the ++ operator. First, like we always do, lets create a list. scala> val list = 0 until 10 toList list: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   scala> val list2 = 10 to 0 by -1 toList list2: List[Int] = List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) And just walk through the operators from here: http://www.scala-lang.org/api/2.11.1/index.html#scala.collection.immutab… The first operator we’ll look at is ++. With this operator we can add two lists together, and return a new one: scala> val list3 = list ++ list2 list3: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)   scala> val list3 = list2 ++ list list3: List[Int] = List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Note that you don’t have to add the same types. Scala will automatically select the most relevant superclass. scala> val list1 = 0 to 10 toList list1: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> val list2 = 10 to 0 by -1 toList list2: List[Int] = List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)   scala> val list3 = list1.asInstanceOf[List[Double]] list3: List[Double] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> list3 ++ list2 res4: List[AnyVal] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) As you can see AnyVal is the most common supertype of both Int and Double so that one gets selected. Now that we’ve seen the ++ operator lets look at one almost the same the ++: operator.With this operator we have the same semantics as ++ but this time the type of the result is determined by the right operand instead of the left one: scala> vector1 res14: Vector[Int] = Vector(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)   scala> list1 res15: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> vector1 ++ list1 res16: scala.collection.immutable.Vector[Int] = Vector(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> vector1 ++: list1 res17: List[Int] = List(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) On to the next two operators :+ and +:. With these two operators we can append and prepend an element to a list: scala> 999 +: list1 res27: List[Int] = List(999, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> list1 :+ 999 res28: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 999) Simple right? Note that the : is always on the side of the list (target). The same goes for the ++: operator we saw earlier. What more do we have? :: and :::. Both these operators add something to the beginning of a list. The :: operator adds a single element, and the ::: operator add a complete list. So basically they are the same as the +: and the ++ operator. The main change is that ++ and +: can be used with Traversable and ::: and :: can only be used with a list. scala> 11 +: list1 res38: List[Int] = List(11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> list1 res39: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> 11 +: list1 res40: List[Int] = List(11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> list2 res41: List[Int] = List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)   scala> list1 ::: list2 res43: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) And then we’ve pretty much covered all except :\ and :/. These functions allow you to fold (see here for more) an list. :\ folds from right to left and :/ folds from left to right. scala> list1 res50: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)   scala> (1 /: list1)((r,i) => {println(i);i+r}) 0 1 2 3 4 5 6 7 8 9 10 res51: Int = 56   scala> (list1 :\ 1)((i,r) => {println(i);i+r}) 10 9 8 7 6 5 4 3 2 1 0 res52: Int = 56 As you can see the folding direction determines whether the elements are processed from beginning to end or backwards. And that’s it for this small snippet.Reference: Scala snippets 2: List symbol magic from our JCG partner Jos Dirksen at the Smart Java blog....

Annotations, Annotations Everywhere

Annotations became available with Java 1.5 in 2004, ten years ago. It’s hard to imagine our code without this feature. In fact, annotations were first introduced to relieve developers from the pain of writing tedious boilerplate code and make the code more readable. Think about J2EE 1.4 (no annotations available) and Java EE 5. Annotation adoption considerably simplified the development of a Java EE application by getting rid of all the configuration XML. Even today, more annotations are being added to the newest version of Java EE. The idea is to unburden the developer and increase productivity. Other technologies and frameworks use them extensively as well.    Annotations Everywhere Let’s see an example on how annotations have simplified our code (from my post about JPA Entity Graphs): Movie.java @Entity @Table(name = "MOVIE_ENTITY_GRAPH") @NamedQueries({ @NamedQuery(name = "Movie.findAll", query = "SELECT m FROM Movie m") }) @NamedEntityGraphs({ @NamedEntityGraph( name = "movieWithActors", attributeNodes = { @NamedAttributeNode("movieActors") } ), @NamedEntityGraph( name = "movieWithActorsAndAwards", attributeNodes = { @NamedAttributeNode(value = "movieActors", subgraph = "movieActorsGraph") }, subgraphs = { @NamedSubgraph( name = "movieActorsGraph", attributeNodes = { @NamedAttributeNode("movieActorAwards") } ) } ) }) public class Movie implements Serializable { @Id private Integer id;@NotNull @Size(max = 50) private String name;@OneToMany @JoinColumn(name = "ID") private Set<MovieActor> movieActors;@OneToMany(fetch = FetchType.EAGER) @JoinColumn(name = "ID") private Set<MovieDirector> movieDirectors;@OneToMany @JoinColumn(name = "ID") private Set<MovieAward> movieAwards; } Wait a minute! Simplified? Really? Aren’t annotations supposed to make my code more readable? This example has more annotations than actual code. To be fair, I’m not including getters and setters. Also, some of the annotated code could be better condensed, but it would make the code harder to read. Of course, this is an extreme case. Anyway, I’m happy since I won the title Annotatiomaniac of the Year. Thanks Lukas!We rely in annotations so much that we end up abusing them. It’s funny that annotations in some cases are causing the same problems that they intended to solve. What if? Let’s rewrite the previous sample like this: Movie.java @MovieEntity @FindAll @LoadWithActors @LoadWithActorsAndAwards public class Movie implements Serializable { @Id private Integer id;@Name private String name;@MovieActors private Set<MovieActor> movieActors;@MovieDirectors private Set<MovieDirector> movieDirectors;@MovieAwards private Set<MovieAward> movieAwards; } It sure looks more readable. But these annotations do not exist. Where do they come from? @LoadWithActors LoadWithActors.java @NamedEntityGraph( name = "movieWithActors", attributeNodes = { @NamedAttributeNode("movieActors") } ) public @interface LoadWithActors {} @LoadWithActorsAndAwards LoadWithActorsAndAwards.java @NamedEntityGraph( name = "movieWithActorsAndAwards", attributeNodes = { @NamedAttributeNode(value = "movieActors", subgraph = "movieActorsGraph") }, subgraphs = { @NamedSubgraph( name = "movieActorsGraph", attributeNodes = { @NamedAttributeNode("movieActorAwards") } ) } ) public @interface LoadWithActorsAndAwards {} And so on for the rest. You get the feeling. The idea would be to extract and group annotation metadata into your own custom annotations. Your annotation could then be used to represent all the annotated data in your code, making it easier to understand. It’s like Java 8 Lambdas, read like the problem statement. Just another example: WoWBusinessBean.java @Named @Stateless @TransactionAttribute(TransactionAttributeType.SUPPORTS) @ApplicationPath("/resources") @Path("wowauctions") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class WoWBusinessBean extends Application implements WoWBusiness {} Rewritten: WoWBusinessBean.java @RestStatelessBean("wowauctions") public class WoWBusinessBean extends Application implements WoWBusiness {} @RestStatelessBean RestStatelessBean @Named @Stateless @TransactionAttribute(TransactionAttributeType.SUPPORTS) @ApplicationPath("/resources") @Path("#{path}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public @interface RestStatelessBean { String value() default "#{path}"; } Usually, I write these annotations once to define the behaviour of my POJO and never look into them again. How cool would be if I could just reuse one annotation for all my Stateless Rest Services? Another nice effect, is that annotation configuration metadata is not directly tied in the code. Instead it’s abstracted away into a different annotation. In this case, it would be possible to override or replace the values in compile / runtime. Meta Annotations I first heard about this concept by David Blevins. He wrote a very good post about these ideas in his Meta-Annotations post and even wrote a possible implementation. It would be convenient to have plain Java SE support to annotation inheritance, abstraction and encapsulation. It’s a major shift in the way annotations are handled by all the technologies out there. This only makes sense if everyone starts supporting this kind of behaviour. One might ask, do we really need this feature? Let’s try to weigh in some pros and cons: ProsSimplified Code. Annotation Reuse. Annotation configuration not directly tied to the code. Values could be overridden.ConsAnother layer of abstraction. Freedom to create custom annotations could obfuscate the real behaviour. Possible to run into some kind of multiple inheritance pitfall.Conclusion It’s unlikely that this Meta-Annotations are going to be available in Java SE for the foreseeable future. In Java 9, most of the focus is in Jigsaw. We don’t have much information yet on Java 10, other than Value Types and Generic Specialization. In fact, all these annotation concerns are not really a problem for plain Java SE. The amount of annotations present in our source files is becoming a problem regarding readability and maintainability. This is especially true for Java EE and other similar technologies. Think about HTML and CSS. If you’re developing an HTML page and you only need a couple of CSS styles, you usually inline them in the elements or include them directly in the page. If you start to have too many styles, then you proceed to extract them into an external CSS file and just apply the style. I do believe that something must be done either by adopting Meta-Annotations or something else. Do you have any other ideas? Please share them! Resources Don’t forget to check David Blevins post about Meta-Annotations. He explains this much better than me, including the technical details. Also a presentation JavaOne EJB with Meta Annotations discussing these ideas by David Blevins. And what better than to listen David Blevins himself? Java EE 7, Infinite Extensibility meets Infinite Reuse.Reference: Annotations, Annotations Everywhere from our JCG partner Roberto Cortez at the Roberto Cortez Java Blog blog....

Camel Subsystem for WildFly 8 integrates Java EE – Getting Started

Just three days ago, the team around Thomas Diesler (@tdiesler) released the 2.0.0.CR1 version of the WildFly-Camel subsystem it allows you to add Camel Routes as part of the WildFly configuration. Routes can be deployed as part of JavaEE applications. JavaEE components can access the Camel Core API and various Camel Component APIs. This release in particular added a number of new camel components to the subsystem and added support for the WildFly domain mode. Other than packaging and bootstrapping Camel in Java EE 7 yourself, this subsystem installs Camel directly into your WildFly 8.x server. As far as I know it even works with the latest 8.2.0.Final but isn’t tested against it. Not, that there is a very light and easy way to bootstrap Camel in Java EE 7, but this approach enables even more integrations with Java EE standards. The ultimate goal for the subsystem is to provide Camel features as a directly usable option in WildFly without the need to configure or deploy anything. This is the main difference between a simple module and a complete subsystem. Getting Started Install WildFly 8.x by downloading the “Java EE7 Full & Web Distribution” from wildfly.org. Install by just extracting it into a folder of your choice. Next step is to download the distribution patch (53 MB, tar.gz) for WildFly from the JBoss Maven repository. After the download, navigate to the WildFly folder and extract the archive into it. That’s it. Now start either standalone or domain mode with the respective *-camel.xml: $ bin/standalone.sh|bat -c standalone-camel.xml Some More Configuration After we did that, you need to add some more users. First of all the management user. $ bin/add-user.sh|bat Call it whatever you like. For convenience reasons I tend to name it admin with the password admin. But please keep in mind, that this is the worst practice you could apply! After you’re done with that, add another application user. To make it simple, we just name it the same with the same, insecure password.   Exploring What’s There After you integrated the subsystem into your WildFly you can find the Apache Camel and JBoss modules in the module folder. The standalone\deployments folder contains two war-files. One of them is HawtIo and the other one is the wildfly-camel.war which is basically the camel-cdi example but more on that later. First of all, point your browser to: http://localhost:8080/hawtio/ and login with the application user you created.You can see, that the ActiveMQ and Camel tabs are enabled, which means both modules have been deployed and discovered by HawtIo. Drilling down into the Camel tab you can see two deployed routes. The versions used for the integration are Apache Camel 2.14.0, HawtIo 1.4.22 and Arquillian 1.1.2.Final. High Level Features The strategy of wildfly-camel is, that a user can “just use” the camel core/component APIs in deployments that WildFly supports already. In other words, Camel should “just work” in standard Java EE deployments. The binaries are be provided by the platform. The deployment should not need to worry about module/wiring details. Defining and Deploying Camel Contexts can be done in different ways. You either can directly define a Context in your standalone-camel.xml server configuration or deploy it as part of your web-app either as a single XML file with a predefined -camel-context.xml file suffix or as part of another WildFly supported deployment as META-INF/jboss-camel-context.xml file. The WildFly Camel test suite uses the WildFly Arquillian managed container. This can connect to an already running WildFly instance or alternatively start up a standalone server instance when needed. A number of test enrichers have been implemented that allow you have these WildFly Camel specific types injected into your Arquillian test cases; you can inject a CamelContextFactory or a CamelContextRegistry as an  @ArquillianResource. Next Steps You can simply undeploy the wildfly-camel.war and start over with your own application. You can either dig into the existing examples on GitHub or wait for my next blog-post to walk you through that a bit. If you don’t want to mess around with installing and patching, you can look at the ready available docker images which were published at wildflyext/wildfly-camel.Reference: Camel Subsystem for WildFly 8 integrates Java EE – Getting Started from our JCG partner Markus Eisele at the Enterprise Software Development with Java blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

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