Featured FREE Whitepapers

What's New Here?


Lean IT fundamentals & principles

The roots of Lean IT are – as the name suggests – in Lean Management. The basic principles of Lean Management had been developed in Toyota’s Production System, that was built back in the 40s of last century. Lean IT is really nothing new, but as an application or adaptation of the basic principles of Lean Management to software development and maintenance the topic not commonly known. The two key elements of Lean IT are the avoidance of waste and continuous improvement process. [1, 2, 3] Lean Transformation  The introduction of lean in a company is also known as Lean Transformation Program. Because it is a big organisational and cultural change, Lean IT is not only the introduction of a single methodology. A Lean Transformation requires actions in several dimensions. The approach of McKinsey considers the following example (4 +1) dimensions: [4]Mindset and Behaviour, Process Efficiency, Performance Management, Organisation & Skills und Voice of the Customer.For each of these dimensions, there is a number of tools, methods and approaches. As part of a Lean Transformation, these are introduced and performed in each single unit/team of the company. The transformation of a working unit/team usually takes between 3-4 months. Afterwards, a continuous improvement process will be setup, to keep the status quo and even get further improvements. Lean IT Principles Steven C. Bell describes in his book ‘Lean IT, Enabling and Sustaining Your Lean Transformation’ following nine principles and/or elements of Lean IT: [5]Respect for People, Pursuit of Purpose, Constancy of Purpose, Proactive Behavior, Quality at the Source, Voice of the Customer, Flow/Pull/JiT, System Thinking und Culture.The following picture shows some of the most important dependencies and relations.Relationship with Agile Development Methods Agile software development methodologies (e.g. SCRUM, XP) and Lean IT are very similar and this is no coincidence, because many of the agile methods and paradigms have their roots in Lean Management. There are some important differences:The popular agile development approaches are highly tailored to self-organizing team. It can work great, if the team members are suitable for self organisation. Lean IT is not based on a self-organizing teams, this means that under Lean IT also classic leadership structures work well. Agile methods are usually limited to insulated working teams and/or composites oft co-located teams. Lean IT is more of an enterprise approach. This is a great advantage, but there is a risk that Lean IT fails for the entire company. Lean IT can be used outside of the actual software development and software maintenance. This is especially true for infrastructure units.Despite all the differences, both approaches have in common is that they try to (i) increase productivity and customer orientation (ii) by means of a continuous improvement process (iii) to achieve increased customer benefits.   Sources and further ReadingsToyota-Produktionssystem; Wikipedia;(Stand2. August2011);http://de.wikipedia.org/wiki/Toyota-Produktionssystem Lean Management; Wikipedia;(Stand2. August2011);http://de.wikipedia.org/wiki/Lean_Management Lean IT; Wikipedia;(Stand2. August2011);http://en.wikipedia.org/wiki/Lean_IT The time is right for lean in payments; (2009); http://www.mckinsey.com/clientservice/Financial_Services/Knowledge_Highlights /Recent_Reports/~/media/Reports/Financial_Services/Lean_In_Payments.ashx Steven C. Bell and Michael A. Orzen; Lean IT, Enabling and Sustaining Your Lean Transformation; Productivity Press; (2010); ISBN-13: 978-1439817568Reference: Lean IT fundamentals & principles. from our JCG partner Markus Sprunck at the Software Engineering Candies blog....

Top 10 Things Every Software Engineer Should Know

Please take a second to look at our brand new Java Resource Collection. The following top ten list collects some important things I have learned in the last eighteen years as IT professional. It is a very personal selection and doesn’t necessarily reflect the opinion of a software engineering organisation. There is no strict ranking in the list – though I tried to put the more important things to the top.The technical and business know-how is more important for young software engineers and the soft skills getting increasingly relevant for senior software engineers. 1) Fundamentals of Emotional Intelligence Almost all of us work with a lot of people. In my first year after university, I had the opportunity to work on a clear big task without any customer and the need to talk a lot with peers. It was pure haven! Just do a complex task and have fun with the compiler. Later the trouble started with more complex tasks, increasing responsibilities and the need to work with people I didn’t liked at all. During my professional life, I attended some so called soft skill courses. In these lesions I learned a lot about communication techniques, negotiation strategies and team dynamics. All this have been mechanical tools or psychological theories. Good to know, but the concept of Emotional Intelligence is something different. The Wikipedia definition of Emotional intelligence starts with the sentence “Emotional intelligence (EI) is the ability to identify, assess, and control the emotions of oneself, of others, and of groups.” [1] The important key word in this sentence is emotions. Emotional intelligencedescribes the role of emotions in our lives. Some years ago, I attended a project meeting with some senior management and the boss of my boss said something to me which sounded like “Hey Markus, you forgot to give me the information XYZ in time!”. I felt embarrassed, like a culprit and explained him that he was not right. The result was that I won the discussion with him and form that day I lost an important supporter in the company. My reaction was stupid and worthless. Yes, I won one battle, but lost the war. The root cause of this disaster was an automatic reaction on my site and a reciprocal effect between this senior management guy and me. With better sens of self and self-regulation, I would have been able to manage the situation in a better way. If you leave sometimes a meeting and say to your self “Oh shit! Why did I say this?”, maybe it would be a good idea to learn something about Emotional Intelligence and yourself. My favorite breakdown of emotional intelligence is:Intrapersonal intelligence describes the ability to have positive relationships and/or good communication between people. This means that you understand what people fell and need. The key competences of intrapersonal intelligence are:Sense of Self: – recognize the own feelings, emotions and reactions – mindfulness to get a better awarenessSelf-regulation – controlling the current inner state – bring own automatic reactions to mind and interruptPersonal leadership – know and lead the parts of your own personalty – care about own strengths and weaknessesInterpersonal intelligence describes the introspective and self-reflective capacities. Know your self, your emotions and what your weaknesses or strengths are, being able to control your own reactions. The key competences of interpersonal intelligence are:Empathy – recognize the feelings and emotions of others – express sympathy in anappropriate wayReduction of Automatic Reciprocal Effects – bring automatic reactionswith othersto mind and interrupt (if needed) Creating Relationships – create mid- and long-term relations with others2) Understand the Business of your Customer How can you design and implement good software without deep understanding of the purpose or use? The answer is easy: “If you don’t know the WHAT, you can’t decide about the HOW.” A deep understanding of your customer’s and/or users’sbusinesswill lead tobetter requirements, designs, implementations and tests.Most of the software’s functionality creates no business value. The challenge is to select the functionality which creates business value. The better you know the business the higher is the probability to implement the best system. 3) Minimum One Programming Language for each Mainstream Development Paradigm The discussion what is the best programming language has a religious character, it’s more a question of belief. I don’t like to preach my personal belief about the bestlanguageshere, but one thing is important: “Learn more programming languages, at least one for each mainstream development paradigms.”procedural programming languages (C, COBOL, PL/I, FORTAN, etc.) object-oriented programming languages (Smalltalk, Java, C++, etc.) functional programming languages (Erlang, Clojure, F#, etc.) declarative programming languages(SQL, XSLT, regular expressions, etc.)Its a good idea to know at least one multi-paradigm programming languages like Python, Java, C++ or C#. You find many listsof programming languages by type or other categoriesin the web [2]. Dependent of your industry, personal preferences and daily tasks you should select your individual top 1o list of programming languages. Learn them and try to use at least 3 of them on a regular base. The old saying “If your only tool is a hammer, all your problems will look like nails” is particularly true for development paradigms. 4) Know your Tools There is a huge number of tools specializing indifferent disciplines like: requirements management, software & database design, software configuration management, build & deploy, continuous integration, development, debugging, profiling, code analysis or testing. It should be mentioned that specialist from infrastructure/operations have also toolboxes with interesting capabilities, e.g. network monitoring, network analysis, operation system analytics, penetration testing, log file analysis, database performance tuning. A software engineer can’t know all tools in detail, but he/she should know the key concepts and underlying technologies. Knowing the right tool and how to use can increase the productivity and quality.Spend some time to learn about tools. 5) Standard Data Structures, Algorithms and Big-O-Notation When I stated to develop software it was absolutely necessary to know a lot about data structures and algorithms. The reason for that was the missing availability of standard implementations. Today most languages have comprehensive libraries for container, sorting and other operations. Still it makes sense to know more. There are two main reasons:correct use of the standard libraries and some times you need individual solutions.You should be able to analyse your own or others code. TheBig-O-Notation is the standard method to describe the expected consumption of time or memory depending from the number of data. [3] If a manual analysis is to difficult, just make a micro benchmark and measure with test data of different size. Draw it in a plot and find a good fit of a possible model function. This is always better than nothing. 6) Don’t Trust Code without Adequate Test Ten years ago, I trusted my code. Why not? After 8 years C++ with excellent skills and a lot of experiences. I just coded, tested and everything was working well. But over the years I made and saw a lot of errors. Because of these errors, I lost the trust in my own and others code. Today, I don’t trust code until it passed:unit test, integration & system tests, checks of performance and memory with real world data, static code analysis, measure code coverage of test, load & stress tests and peer review.This sounds over engineered, but you have to spend the time either during development or during maintenance. I favor to do the work once with good quality and not to spend my time withtroubleshooting. 7) Basics of Project Management, Lean Management and Agile Concepts Even you don’t like to work as a project manager, you work in teams and at least have to organize your own work. To get along with technical leads you should understand their wording and way of thinking. Today everybody can work as project manager, scrum master or technical lead. Spend time to learn about management, because sometimes you should manage these guys. A good example is effort estimation. My personal experiences say, that if you ask a software engineer about the effort of a task you get in 80% of the cases a dramatic underestimation of the effort. A software engineer tends to estimate just the good case without unexpected problems. This causes delays and/or poor quality because quite often the unexpected problems just happen.An other problem is the Definition of Done. The project manger means everything is done and often the developer estimates just the technical stuff. Last week I had such a case. The developer estimated just one week of work. And after a complete planning, we saw several months effort. The developer estimated the time for implementation and forgot to estimate documentation, security concept, data protection issues, alignment with workers councils, reviews, project management efforts, deployment, etc. 8) Key Metrics of Software Development Know what happens in your software, process, team and your own work. It is very difficult to control something what you can’t count. I encourage you to have question and try to find a real world measure as answer. Then you can have target values, do your work and find out if it worked out. Important is the word “real world measure”. In software engineering we find a lot of obscure measures and/or derived metrics. E.g. the so calledmaintainability index (MI) [4]: MI = 171 – 5.2 x ln(avgHV) – 0.23 x avgCC(g‘) – 16.2 x ln (avgLOC) + 50 x sin (sqrt(2.4 x perCM)) where HV is the Halstead Volume, CC is the Cyclomatic Complexity, LOC is the lines of code and perCM is the percentage of comment lines. This is not what I call a real world measure and I don’t understand this. My advice is easy: “Never use a measure and/or metric you don’t understand 100%. Some times it is enough to take some glasnuggets and count them (see also How Lean IT helps to reduce waste due to interruptions in software development?).” 9) The Root Cause of the Last Defect Maybe your last error was not as severe, but to learn more about the root cause and negative effects   you should analyse it.What was the root cause? In what development phase came the error in the software? How could it be detected earlier? Would a tool help to avoid it? Would a rule help to avoid it? Was it a qualification problem? Is the working environment (lot of interruptions, etc.) the root cause? Is it an documentation problem? Or maybe a communication problem? What are the costs to fix it? Are in the affected component more errors? Are the test cases good/complete enough?You see a lot of question and the list is still not complete. The most important point is, to find the root cause to get better over the time. This works for your own qualification and way of working. And it works for your team. You just have to ask some question. 10) Understand the Infrastructure I spend the my first 10 years in IT without thinking more than a minute about infrastructure. It was not necessary, because I didn’t work in an enterprise environment. At the moment I work for a bank (sorry for these Lehman Brothers stocks, nobody asked me). In a bank you have a lot of these infrastructure people. They are really different form software engineers. But, I don’t like to discuss here the differences and possibilities to get along with them. Important is their language. Infrastructure peoples talk in “Information Technology Infrastructure Library (ITIL)”. Spend at least some days to learn this ITIL terminolgy. [5]Some terms are completely different uses as developers do. The second important thing is, that in infrastructurethe people are much more specialized than developers. Sometimes a developer has just one question and needs five infrastructure guys for the answer. The ITIL stuff is maybe the glue between the people ininfrastructure. Further Readinghttp://en.wikipedia.org/wiki/Emotional_intelligence  http://en.wikipedia.org/wiki/Categorical_list_of_programming_languages http://www.leepoint.net/notes-java/algorithms/big-oh/bigoh.html http://www.virtualmachinery.com/sidebar4.htm  http://en.wikipedia.org/wiki/Information_Technology_Infrastructure_LibraryReference: Top 10 Things Every Software Engineer Should Know from our JCG partner Markus Sprunck at the Software Engineering Candies blog....

Application Security at Scale

This week’s SANS AppSec conference in Las Vegas took on Application Security at Scale: how can we scale application security programs and technologies to big organizations, to small organizations and across organizations to millions of programmers world wide. You can find the presentation slides here. Lots of hilights for me: The conference was kicked off by Jeremiah Grossman from WhiteHat Security who made it clear that the problem of web application security alone is much bigger than we can take care of with the people and technology that we have today. We need to try different things like:Game-ification: get developers interested and involved in Appsec using games and challenges like capture-the-flag, or the Elevation of Privilege card game (a game I have to try out) Use peer pressure and score cards between teams, products, business units – drive better application security through competition (as we learned later, Cisco is one of the organizations score carding business units and products to drive improvement in software security programs) Good, simple (and I will add inexpensive) online training to get as many developers as possible up to speed on secure design and coding Write good, usable security frameworks and libraries and build security in by default into the major application frameworks – unfortunately we don’t know what frameworks will get widely adopted until they are widely adopted, so we will always be playing catch-up Build security into the developer’s workflow – this is what SD Elements is doing Use WAFs and virtual patching where it makes sense – to raise the bar on attacks by plugging simple issues found by scanners (WAFs used properly could block more than 2/3 of web application vulnerabilities, the kinds that scanners find); and to secure legacy code that nobody wants to try to figure out and fix by hand or in shops where it is too expensive and slow to get fixes out (in many Agile / Devops shops, it’s faster to fix and deploy the code than it is to put in a patch to the WAF). Bug Bounty programs – if this works for Google and Facebook, it could work for you.Chris Eng at Veracode presented some metrics collected from the scans that they have done for customers over the past 18 months. The interesting thing for me was the correlation between attack data (from the Verizon 2011 Data Breach Report)and vulnerability data, the intersections highlighting what we need to focus on. Just like last year (and the year before) SQL injection is the leading problem: 32% of apps scanned had SQL injection vulnerabilities, 20% of attacks are SQL injection. The XSS Problem (and some Solutions) According to Veracode’s data, 68% of web apps have XSS vulnerabilities. This is no surprise after you listen to Jim Manico explain in detail what programmers have to do to prevent XSS. Even getting every developer building web apps to understand all of the different rules for context-correct output encoding and escaping isn’t going to solve the problem: there are too many details for developers to take care of without missing something or making mistakes. “It’s more complex to stop XSS in large-scale apps than it is to do applied crypto and key management properly…. We have never seen a web app that can’t be attacked through XSS”. But there is hope – in a later presentation he explained how Context-Aware Auto-Escaping (aka Auto-Encoding) technology like JXT (a close-to-drop-in replacement for JSP, if you are writing well-formed JSP) and Ivan Ristic’s work on Apache Velocity Auto-Escaping can help protect at least some web apps from XSS. The most promising new technology for me was HTML5 iFrame Sandboxing which looks like it could actually be dropped in today to protect apps, at least if your customers are using modern browsers. I also learned about JavaScript object freezing and sealing to help protect rich client apps. I was on a panel that looked at application security in small companies, together with Nick Galbreath at Etsy and Cameron Morris at Partnet – a small company that builds online web shopping portals for the US DoD. At Partnet everyone owns security: many of the developers have been trained on application security, all of them understand the OWASP Top 10, all code that is checked in is reviewed. I presented a case study on our AppSec program, what worked and what didn’t for us, from startup to now. Nick built on an earlier presentation by Zane Lackey at Etsy which explained some of the security controls in Etsy’s frameworks and Continuous Deployment pipeline, and the extensive monitoring and instrumentation feedback loops that they have from production back into development. This includes cool automated checks on changes to high-risk code (they have automated tests that hash specific pieces of code, if the hash value changes the build system automatically alerts the AppSec team and provides them the change set for code review). Being able to deploy several times a day means that they can deploy new code (including security fixes) extremely quickly with high confidence. Nick also presented on rate limiting to monitor and control event activity in production. I am critical of Continuous Deployment – too many people who try to follow this model put speed ahead of reliability and security, and unnecessarily put their customers at risk. They don’t know when they have crossed the line from a web startup to running a real business. But if you are going to try this and want to do it right, learn everything that you can from Etsy. Mobile AppSec – Android is a Train-Wreck From the panel on mobile Appsec: Google has a good page on writing secure apps for Android (I am guessing it is this page) but it’s clear that most developers don’t know about it. The consensus was that Apple’s IOS is the most secure smart phone platform, and Android is a train wreck – according to one of the researchers (Georgia Weidman at Bulb Security), 1/2 of the default Android apps have serious security vulnerabilities. Secure Frameworks and APIs Chenxi Wang’s Day 2 keynote emphasised the importance of isolating security code and sharing and reusing security code through APIs. This was reinforced in a later panel by Jason Chan at Netflix and Adam Migus at E*Trade – like us, both these organizations rely on simple, extensible secure frameworks or APIs that developers can use to take care of problems like identity management, permissioning, crypto, secure transport, validation. At E*Trade, they find that most security vulnerabilities are because developers didn’t use this code (or didn’t use it properly). It doesn’t cost that much to write and support a secure framework – a few smart people can take care of this for the rest of the organization. And there are Open Source examples today like Apache Shiro that we can use to solve a lot of common security problems. Pen Testing An excellent panel on “inside the mind of a pen tester”, how expert pen testers think and work and approach problems, the tools that they use (I learned about chaining multiple attack proxies like Burp Suite and Zap together to take advantage of the different strengths of each tool). The most important thing in the pen test is for developers and management to get a clear understanding of the risks in the application: what kind of problems the testers found, how serious were they, what you have to do to fix them and what you have to do to prove that you fixed them. The real value of pen testing, like any other kind of testing, is the information that you get out of the test. If you’re not learning from pen tests, if the next time the tester comes back and tests the same system and finds the same problems, what are you paying for? These pen testing experts had mixed opinions of WAFs – if a customer has a WAF it is usually installed out-of-the-box without tuning, and doesn’t present more than a speed bump to a determined attacker. But like anti-virus protection, it will stop most drive-by attacks – some big sites are seeing that as much as 10% or even 20% of their traffic is potentially dangerous, and a good WAF should be able to catch at least some of this. Most memorable quotes from the conference There is no such thing as an internal application. Jeremiah Grossman, WhiteHat Security You can checkbox compliance but you can’t checkbox security. Monica Bush, University of Wisconsin-Madison The closing message was sobering. We need more people who understand AppSec and who can write secure code – a lot more people. Big companies may only have a few AppSec generalists supporting thousands of developers, most companies don’t have anyone at all. This isn’t enough. Point-in-time assessments like pen tests aren’t enough either, because the attack space is always changing and the code is always changing – in a few weeks or months at most the results of a pen test may be invalidated. What we are doing today isn’t enough and it’s not going to scale. We need more security burned in and we need continuous security testing, which means more people who understand AppSec and better and more effective tools. Reference: Application Security at Scale from our JCG partner Jim Bird at the Building Real Software blog....

REST endpoint for integration using Apache Camel

REST is an architectural style used for organizing resources and when applied to HTTP-based services allows building stateless, decoupled, scalable services. HTTP methods, HTTP headers, and mime-types all allow a developer to achieve the REST style. Frameworks like Jersey and Fuse Services Framework (Apache CXF) can be used to speed up the development and deployment of services trying to achieve a RESTful style, and in this blog post I’d like to discuss how to build the backend of a resource that relies on integration provided by Fuse Mediation Router also known as Apache Camel. Just as an aside, a link that I’ve had tucked away in the recesses of my bookmarks may be of interest for those of you wondering whether your architecture is indeed RESTful or just the same highly coupled RPC style that REST tries to alleviate. Roy Fielding, who wrote his dissertation on REST, actively asserts the notion that hyerlinks within resource representations are a must for REST styles, and even further clarifies the uncertainties around implementing REST. The source code for this sample can be found on my github repository Fuse Mediation Router is FuseSource’s enterprise-grade, hardened version of Apache Camel that provides a comfortable DSL for describing integrations, mediations, and routing. It’s free, open-source, and has an Apache License. For those unfamiliar with Mediation Router/Camel, take a look at an introduction from Jon Anstey (co-author of Camel in Action)at DZone’s Enterprise Integration Zone: Apache Camel: Integration Nirvana. We will be using Mediation Router to help write a simple integration between a REST endpoint and a resource files on a file system. I’ll be using camel-cxfrs component to expose the REST endpoint and will be using the camel-file component to read a directory on the file system. The intention of the sample is to describe the configuration necessary to expose the REST interface with Mediation Router, integrate with a backend somehow, transform the data into an appropriate REST response, and send back the response. To get started, let’s focus on how to set up the REST endpoint. To do so, you would create a JAX-RS resource that describes the java methods that will act as REST endpoints. This sample code requires familiarity with Java API for RESTful Web Services aka JAX-RS. For those unfamiliar, here are some great tutorials to follow along that help to understand JAX-RS. @Path("/customerservice/") public class CustomerServiceResource {// NOTE: The instance member variables will not be available to the // Camel Exchange. They must be used as method parameters for them to // be made available @Context private UriInfo uriInfo;public CustomerServiceResource() { }@GET @Path("/customers/{id}/") @Produces("text/xml") public Customer getCustomer(@PathParam("id") String id) { return null; }@PUT @Path("/customers/") public Response updateCustomer(Customer customer) { return null; }}As you can see, the annotations are the JAX-RS annotations that describe the operations, HTTP methods, and mime-types involved with the REST endpoint. Notice, the return values are all null as this class will not actually be used to handle the requests that come in to the endpoint; the Mediation Router routes will be responsible for processing and responding. Note, however, that instance members are not available to the Mediation Router exchanges, i.e., any instance members injected via the JAX-RS @Context annotations will not be available. To make them available, add them as parameters to your methods. Declaring the CXF-RS endpoint with Mediation Router can be done one of two ways: Directly in the endpoint configuration like this: from("cxfrs://http://localhost:9090/route?resourceClasses=com.fusesource.samples.CustomerServiceResource")Creating it directly in the configuration requires less xml configuration but offers limited flexibility. Another option is creating a separate bean that’s responsible for the endpoint and then referencing it within the endpoint configuration: from("cxfrs:bean:rsServer")The bean rsServer should be defined in the camel context. An example: > <cxf:rsServer id="rsServer" address="http://localhost:9090/route" serviceClass="com.fusesource.samples.CustomerServiceResource"/>This approach allows you to decouple the endpoint configuration and allows to be quicker and less verbose in the endpoint configuration. Both options are shown in the sample code, although the first option is used. That’s all the configuration required to expose the REST endpoint with Mediation Router. Fairly simple. The next step is to consume a file from the file system based on what comes in from the REST endpoint. The contents of the file will be returned to the client of the REST call. To do this, we use the camel-file component and enrich the Exchange with a pollEnrich call in the DSL: .setHeader(Exchange.FILE_NAME, simple("test-${body}.xml")) .pollEnrich("file:src/data?noop=true", 1000, new CustomerEnricher())We cannot use any dynamic expressions in the pollEnrich call, so we set a header that the file component understands before we do the enrichment. In this case, the body of the REST message is an identifier that can be used to template the file-system resource. Lastly, we can attach some additional processing to the route: .process(new CustomerServiceProcessor())The intent of the example, as described above, is to show how to configure the endpoint and attach it to further Mediation Router processing. Note, the Message Exchange Pattern (MEP) for the REST endpoint is InOut and expects a response. The example is not meant to be a complete end-to-end solution as that will vary depending on intended functionality. Please note above the links to Roy’s discussions on what REST is and is not. If I have left something out, or you need more clarification around the example, drop me a comment and we can discuss. Reference: REST endpoint for integration using Apache Camel from our JCG partner Christian Posta at the Christian Posta Software blog....

GWT and HTML5 Canvas Demo

This is my first experiment with GWT and HTML5 Canvas. My first attempt is to create rectangles, with just a few lines of code I came up something like this:Code:public class GwtHtml5 implements EntryPoint { static final String canvasHolderId = "canvasholder"; static final String unsupportedBrowser = "Your browser does not support the HTML5 Canvas"; static final int height = 400; static final int width = 500; final CssColor colorRed = CssColor.make("red"); final CssColor colorGreen = CssColor.make("green"); final CssColor colorBlue = CssColor.make("blue"); Canvas canvas; Context2d context; public void onModuleLoad() { canvas = Canvas.createIfSupported(); if (canvas == null) { RootPanel.get(canvasHolderId).add(new Label(unsupportedBrowser)); return; } createCanvas(); } private void createCanvas(){ canvas.setWidth(width + "px"); canvas.setHeight(height + "px"); canvas.setCoordinateSpaceWidth(width); canvas.setCoordinateSpaceHeight(height); RootPanel.get(canvasHolderId).add(canvas); context = canvas.getContext2d(); context.beginPath(); context.setFillStyle(colorRed); context.fillRect(100, 50, 100, 100); context.setFillStyle(colorGreen); context.fillRect(200, 150, 100, 100); context.setFillStyle(colorBlue); context.fillRect(300, 250, 100, 100); context.closePath(); } }And my Spring balls experiment with some codes that I found on the Web.Reference: GWT and HTML5 Canvas Demo from our JCG partner Mark Anro Silva at the GlyphSoft blog....

Spring 3 and Java EE 6 – An unfair and incomplete comparison

The first draft of this small article had the title ‘Spring & Java EE – Comparing Apples and Oranges’. During writing this, I learnt that it is possible to compare Spring Framework and Java EE, but it is always an unfair and incomplete work. The evolution of Java for Enterprise and Spring Framework are strongly connected to each other. Both leaned from each other and partly copied good concepts. In Table 1 you can see a simplified timeline with some key milestones of Java Platform for Enterprise and Spring Framework. This table explains, that it makes only sense to compare Java EE v6 with Spring v3.0. Earlier versions of Spring Framework and J2EE are outdated and Java EE v7 is still not published (actually delayed to Q2 2013). Table 1: Timeline of Java Platforms and Spring FrameworkYear Java Platform, Standard Edition Java Platform, Enterprise Edition Spring Framework Key Milestones2000 J2SE v1.3J2EE v1.2.1EJB 2 – difficult deployment descriptors – difficult testing – lot of redundantartifacts2001J2SE v1.320022003 J2SE v1.4 J2EE v1.42004Spring v1.0 First Spring Framework – dependency injection (IoP) – no Java EE application server -competitor to J2EE2005Spring v1.22006 J2SE v5 Java EE v5 Spring v2.0 Java EE 5 (EJB 3.0) – a lot of functions inspired by Spring – elimination of component, home and remote interfaces2007Spring v2.520082009 Java SE v6 Java EE v6 Spring v3.0 Java EE 6 (EJB 3.1) – interfaces are optional – singleton beans – cron-like scheduling – embeddable containers Spring 3.0 – Spring Expression Language – MVC-Framework with improved REST support20102011 Java SE v 7Spring v 3.1So, in table 2 the main building blocks of Spring Framework are listed. The Inversion of Control Container is the core function of Spring Framework. To understand how this works you may also check A minimal Java application based on Spring framework(sample code uses Spring 2.5.6.A, but the main principles are the same for Spring 3.0). Table 2: Selected Building Blocks of the Spring v3.0 FrameworkInversion of Control Container - Inversion of Control – Dependency Injection – Configuration with XML files and/or annotations (auto wiring)Model-View-Controller Framework - Domain objects (Models) -Usually JSP templates (Views) -DispatcherServlet as front-controller for ControllerAspect-Oriented Programming Framework - Basic AOP for cross-cutting concerns in aspects – Interception based and is configured at runtime – Configuration with XML files and/or annotationsBatch Framework -Processing large volumes of records or tasks.Including: logging, tracing, transactions, job management, resource management, exception convertingData Access Framework - Support is provided for popular frameworks – JDBC, iBatis, Hibernate, JDO, JPA, Oracle TopLink, Apache OJB, and Apache CayenneTransaction Management Framework - Abstraction mechanism (JTA only supports nested transactions and global transactions, and requires an application server)Remote Access Framework - Working with various RPC-based technologies available on the Java platform both for client connectivity and exporting objects on serversSource & Further Reading: http://en.wikipedia.org/wiki/Spring_Framework In table 3 the main standards and components of the Java Platform, Enterprise Edition 6 are listed. This table makes clear that Java EE 6 contains of a lot of standards and is not just a framework. Table 3: Selected Building Blocks of the Java EE 6 ArchitectureSource of Picture The Java EE 6Tutorial,p39 Client Machine – Java Server Faces (JSF 2.0) – JSP Standard Tag Library (JSTL) – Ajax with JavaServer Faces Technology – Facelets (XHTML) – Support for the Expression Language (EL) – Templating for components and pages – Java Servlet Technology (Servlet 3.0) – Internationalizing and Localizing Web Applications Java EE Server – Enterprise JavaBeans (enterprise bean) components – JAX-RS RESTful web services – JAX-WS web service endpoints – Enterprise Beans as POJO (Session and Message-driven) – Managed Beans as POJO – Interceptors – Dependency Injection for Java (JSR 330) – Contexts and Dependency Injection, CDI (JSR 299) – Annotations to minimize deployment descriptor needs – Asynchronous method invocation in session beans – Declarative and programmatic security – Java Message Service (JMS) API – Java Persistence API entities Persistence – Java Database Connectivity API (JDBC) – Java Persistence API 2.0 – Java EE Connector Architecture – Java Transaction API (JTA)Source & Further Reading: http://olex.openlogic.com/wazi/2010/get-started-with-jee6/ Practical Experiences When I started to learn Spring Framework 3.0 some years ago, I implemented a small web application with a lot of Spring functions. To be honest, more than necessary for this task. This small application had extensive test code for unit and integration test automation. It has 100% line and branch coverage. Some time later, I decided to implement exactly the same application based on Java EE 6 Architecture to compare the two approaches.Both technologies worked well, have almost the same code size and a good maintainability. One significant difference is the support of testing. Spring Framework has an excellent support for testing and Java EE 6 has here some weaknesses. For Java EE 6 you can use Embedded Glassfish, but this approach is annoying slow (long start-up time for embedded container) and touchy in the configuration. A further outstanding feature of Spring Framework is the easy integration of legacy applications. It is easier to renew an old application in a step by step approach, e.g. with JDBC, transaction management and small parts of IoC in the beginning. ConclusionForm the architectural point of view the models of Spring and Java EE are competitors. Depending on the strategy and constraints of your organization both show strengths and weaknesses. A combination of both can’t generally be recommended, because it is either waste of the EJB Container functionality and/or difficult to maintain. In some selected cases, it may make sense to use Building Blocks of Spring Framework in a Java EE 6 application, e.g. Spring Batch, Data Access. Spring Framework is not a standard – it is a product and an implementation of a framework. This means, there is no alternative vendor. Please, keep this always in mind.Reference: Lightweight Java Enterprise Architectures – An Unfair and Incomplete Comparison Between Spring 3 Framework and Java EE 6 from our JCG partner Markus Sprunck at the Software Engineering Candies blog....

Spring MVC 3 Controller for MyBatis CRUD operation

Till now we have created CRUD database service for the domain class “User” and alsointegratedMyBatis configuration with Spring Configuration file. Next, we will create an web page using Spring MVC to use MyBatis CRUD service to perform operations to database.Creating DAO class using MyBatis 3 that will help to perform CRUD operations on database. Setting Environment for integrating MyBatis 3 and Spring MVC 3 frameworks. Creating Spring MVC 3 controller for performing CRUD operation.So, in this part we will go through following sessions that will make us able to create the user interface for the example using Spring MVC and MyBatis CRUD service:The Spring Form Validator The Spring MVC Controller The jsp page andJavaScriptfiles used to perform UI creation And the last Spring MVC configuration fileThe Spring Form Validator First of all we will see the form validator used in this example. Here is the code: package com.raistudies.validator;import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator;import com.raistudies.domain.User;@Component public class RegistrationValidator implements Validator {public boolean supports(Class<?> c) { return User.class.isAssignableFrom(c); }public void validate(Object command, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.name.empty"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "standard", "field.standard.empty"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "field.age.empty"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "sex", "field.sex.empty"); User usrBean = (User)command; if(!isNumber(usrBean.getAge().trim())) errors.rejectValue("age", "field.age.NAN"); }private boolean isNumber(String str){ for (int i = 0; i < str.length(); i++) {//If we find a non-digit character we return false. if (!Character.isDigit(str.charAt(i))) return false; }return true; } }As you can see, we have put some restrictions on the form values like every field should have values and the value in “ age” field should be number. You can add more restrictions on the form values as you need from the validate() method of this class. The contain of the error message values are defined in the property file messages.properties, which is as bellow: field.name.empty=Name field is mandatory. field.standard.empty=Standard field is mandatory. field.age.empty=Age field is mandatory. field.sex.empty=Sex field is mandatory.field.age.NAN=Age should be a number.That is all for the form validation part, now we will see controller part. The Spring MVC Controller The controller will project the request from browser to MyBatis services. Bellow is the code: package com.raistudies.controllers;import java.util.List; import java.util.UUID;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;import com.raistudies.domain.User; import com.raistudies.persistence.UserService; import com.raistudies.validator.RegistrationValidator;@Controller @RequestMapping(value="/registration") public class RegistrationController {private RegistrationValidator validator = null; private UserService userService = null;@Autowired public void setUserService(UserService userService) { this.userService = userService; }public RegistrationValidator getValidator() { return validator; }@Autowired public void setValidator(RegistrationValidator validator) { this.validator = validator; }@RequestMapping(method=RequestMethod.GET) public String showForm(ModelMap model){ List<User> users = userService.getAllUser(); model.addAttribute("users", users); User user = new User(); user.setId(UUID.randomUUID().toString()); model.addAttribute("user", user); return "registration"; }@RequestMapping(value="/add", method=RequestMethod.POST) public ModelAndView add(@ModelAttribute(value="user") User user,BindingResult result){ validator.validate(user, result); ModelAndView mv = new ModelAndView("registration"); if(!result.hasErrors()){ userService.saveUser(user); user = new User(); user.setId(UUID.randomUUID().toString()); mv.addObject("user", user); } mv.addObject("users", userService.getAllUser()); return mv; }@RequestMapping(value="/update", method=RequestMethod.POST) public ModelAndView update(@ModelAttribute(value="user") User user,BindingResult result){ validator.validate(user, result); ModelAndView mv = new ModelAndView("registration"); if(!result.hasErrors()){ userService.updateUser(user); user = new User(); user.setId(UUID.randomUUID().toString()); mv.addObject("user", user); } mv.addObject("users", userService.getAllUser()); return mv; }@RequestMapping(value="/delete", method=RequestMethod.POST) public ModelAndView delete(@ModelAttribute(value="user") User user,BindingResult result){ validator.validate(user, result); ModelAndView mv = new ModelAndView("registration"); if(!result.hasErrors()){ userService.deleteUser(user.getId()); user = new User(); user.setId(UUID.randomUUID().toString()); mv.addObject("user", user); } mv.addObject("users", userService.getAllUser()); return mv; } }The controller is using two beans for the CRUD operations, one is RegistrationValidator that we say above to validate the form data and other is UserService that we created in our previous part using MyBatis 3 to perform database operations on the form data. Both the beans will beauto wiredby spring using setter injection. The controller have following operation methods that handles CRUD requests on form data:showForm() :This operations will show up the form for the first time that is why we have put method type as RequestMethod.GET The method will also provide all available users in database using getAllUser() method of UserService to show up on the table bellow the form. add() : This operation will handle the create operation. First of all it will validate the form data and if no erroroccurthen it will save form data to database to create a new user usingsaveUser()method of UserService. It will also bind a new User object with the form. update() : update method will update the user detail to the database using updateUser() method of UserService and before that it will validate the data using RegistrationValidator. delete() :This method is used to delete the user from database and take helps from the deleteUser() method of UserService for this.The jsp page and JavaScript files used to perform UI creation In this session, we will see user interface part of the example. We are to create a web page like the following :Spring MVC and MyBatis 3 Integration – User FormUI functionality:The “Save Changes” button will be used to create a new user or to update an existing user. The “New User” button will be used to set the form to create a new user. The “Delete User” button will be used to delete a user who’s details are showing in the form Clicking on any row will bring the corresponding row data to form fields for update or delete.Let us see jsp code corresponding to the web page: </div> <div> <pre><!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%@ page session="true" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Hello World with Spring 3 MVC</title> <meta http-equiv="Content-Type" content="text/html; charset=windows-1251"> <script type="text/javascript" src='<c:url value="/resources/common.js"/>'></script> <script type="text/javascript" src='<c:url value="/resources/registration.js"/>'></script> <script type="text/javascript"> var projectUrl = '<c:url value="/"/>'; if(projectUrl.indexOf(";", 0) != -1){ projectUrl = projectUrl.substring(0, projectUrl.indexOf(";", 0)); } </script> </head> <body> <fieldset> <legend>Registration Form</legend> <center> <form:form commandName="user" action="/SpringMVCMyBatisCRUDExample/app/registration/add" name="userForm"><form:hidden path="id"/> <table> <tr><td colspan="2" align="left"><form:errors path="*" cssStyle="color : red;"/></td></tr> <tr><td>Name : </td><td><form:input path="name" /></td></tr> <tr><td>Standard : </td><td><form:input path="standard" /></td></tr> <tr><td>Age : </td><td><form:input path="age" /></td></tr> <tr><td>Sex : </td><td><form:select path="sex"> <form:option value="Male"/> <form:option value="Female"/> </form:select></td></tr> <tr><td colspan="2"><input type="submit" value="Save Changes"/> &nbsp;<input type="reset" name="newUser" value="New User" onclick="setAddForm();" disabled="disabled"/> &nbsp;<input type="submit" name="deleteUser" value="Delete User" onclick="setDeleteForm();" disabled="disabled"/></td></tr> </table> </form:form> </center> </fieldset> <c:if test="${!empty users}"><br /> <center> <table width="90%"> <tr style="background-color: gray;"> <th>Name</th> <th>Standard</th> <th>Age</th> <th>Sex</th> </tr> <c:forEach items="${users}" var="user"> <tr style="background-color: silver;" id="${user.id}" onclick="setUpdateForm('${user.id}');"> <td><c:out value="${user.name}"/></td> <td><c:out value="${user.standard}"/></td> <td><c:out value="${user.age}"/></td> <td><c:out value="${user.sex}"/></td> </tr> </c:forEach> </table> </center> <br /></c:if> </body> </html></pre> </div> <div>As you can see, the default action of the form is to add the form detail to database using add method of the controller. On click of “Delete User”, it will call a JavaScript function that will change the form url to delete the user. We have used<c:forEach/> jstl for showing all the users on the table and every row hasdeclaredon click even which will bring the table row data to form and also will change the form submit url to call update() method of controller. Spring MVC configuration file At last we will see the Spring MVC configuration that has been using to configure the controller and all other things. Following is the configuration file : </div> <div> <pre><?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><!-- Application Message Bundle --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages" /> <property name="cacheSeconds" value="3000" /> </bean><!-- Scans the classpath of this application for @Components to deploy as beans --> <context:component-scan base-package="com.raistudies" /><!-- Configures the @Controller programming model --> <mvc:annotation-driven /><!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean><import resource="jdbc-context.xml"/> </beans></pre> </div> <div>The configuration file includes themessages.properties as resource bundle and also includejdbc-context.xml configuration files which contains configuration for integration MyBatis 3 with Spring. While running the example you will get the above screen as out put that will also show all the records present in database. Click on the “Save Changes” button you will get following screen that will show you validation errors on the blank form values:Spring MVC and MyBatis 3 Integration – User Form with validation errors Now fill the form with valid data and and click on the “Save Changes” button, it will bring the form data to bellow table. That is all from this example. Hope that you have enjoyed the learning!!Creating DAO class using MyBatis 3 that will help to perform CRUD operations on database. Setting Environment for integrating MyBatis 3 and Spring MVC 3 frameworks. Creating Spring MVC 3 controller for performing CRUD operation.You can download the source code and war file from following links: Source (Eclipse Project without jars) :Download War (With jars) :Download Reference: Spring MVC 3 controller for performing CRUD operation using MyBatis(iBatis) 3 from our JCG partner Rahul Mondal at the Rai Studies blog....

Publishing Play 2 modules on github

Now you’ve doubtless followed my earlier guides on writing modules for Play 2, I imagine you’re keen to show your coding chops to the world. The problem is – and this is quite a big one, I’m afraid – there is no place to publish your modules to. When I first starting writing Play modules, the repository was already set-up and ready to go – however, it used a custom format (state of the art download-and-unzip). This changed to some degree with Play 1.2, but I have to say I’m not a fan of that dependency management mechanism; I’m just too damn old to learn these shiny new things. With Play 2, things swung around again and the dependency mechanism is compliant with Maven and Ivy. I can hear enterprises up and down the planet rejoicing. However, this still doesn’t help you achieve your well-deserved glory and fame, unless you happen to host your own Maven/Ivy repo or feel like hacking the auto-generated artifact models that Play generates. Help is hand, until Play 2 modules have an official release mechanism, using GitHub’s Pages feature. Very simply, we’ll use Play’s publish-local task to generate all the files we need in the correct directory structure, and then copy that structure as-is directly into GitHub pages. A publish in this manner can be done in less than a minute, after you’ve done the initial set-up in GitHub. Creating the repository in GitHub If your GitHub user name is, for example, foo, then creating a repository called foo.github.com hooks you into Pages – what you commit here will be available at http://foo.github.com. There’s no GitHubby goodness when it comes to displaying files here – what you commit is what’s available in its native form. Commit a HTML file (let’s call it bar.html), and point your browser at http://foo.github.com/bar.html and you’ll see the rendered HTML – not the source of it. This makes it ideal for exposing files that you want represented in their raw form – say, the jar file containing your Play 2 module. So, go ahead and create a .github.com repository and clone it to your workspace, and cd into it. In here, you can replicate (kind of – see later) a meven repository. To keep things nice, the first directory you should create is releases. If you also want to add a snapshot directory, do it at this level. Note: When you first create the repository in GitHub, it can take up to 10 minutes for it to become available. If you haven’t changed your email preferences, you should receive a notification when it is ready. This doesn’t stop you committing to the repository in the meantime. Publish the files locally Let’s assume your module name is hurdy as the artifact name. Your Build.scala looks like this: import sbt._ import Keys._ import PlayProject._object ApplicationBuild extends Build {val appName = "hurdy" val appVersion = "1.0"val appDependencies = Seq( )val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings( ) }(The mainLang value may be something else, depending on your primary language). In the root of your module, start up Play and publish it locally: steve@hex:/tmp/hurdy$ play [info] Loading project definition from /tmp/hurdy/project [info] Set current project to hurdy (in build file:/tmp/hurdy/) _ _ _ __ | | __ _ _ _| | | '_ \| |/ _' | || |_| | __/|_|\____|\__ (_) |_| |__/play! 2.0, http://www.playframework.org> Type "help play" or "license" for more information. > Type "exit" or use Ctrl+D to leave this console.[hurdy] $ clean [success] Total time: 0 s, completed Apr 21, 2012 9:49:00 AM [hurdy] $ compile [info] Updating {file:/tmp/hurdy/}hurdy... [info] Done updating. [info] Compiling 4 Scala sources and 2 Java sources to /tmp/hurdy/target/scala-2.9.1/classes... [success] Total time: 7 s, completed Apr 21, 2012 9:49:08 AM [hurdy] $ publish-local [info] Packaging /tmp/hurdy/target/scala-2.9.1/hurdy_2.9.1-1.0-SNAPSHOT-sources.jar ... [info] Done packaging. [info] Wrote /tmp/hurdy/target/scala-2.9.1/hurdy_2.9.1-1.0-SNAPSHOT.pom [info] :: delivering :: hurdy#hurdy_2.9.1;1.0-SNAPSHOT :: 1.0-SNAPSHOT :: release :: Sat Apr 21 09:49:12 CEST 2012 [info] delivering ivy file to /tmp/hurdy/target/scala-2.9.1/ivy-1.0-SNAPSHOT.xml [info] Generating API documentation for main sources... [info] Packaging /tmp/hurdy/target/scala-2.9.1/hurdy_2.9.1-1.0-SNAPSHOT.jar ... [info] Done packaging. model contains 23 documentable templates [info] API documentation generation successful. [info] Packaging /tmp/hurdy/target/scala-2.9.1/hurdy_2.9.1-1.0-SNAPSHOT-javadoc.jar ... [info] Done packaging. [info] published hurdy_2.9.1 to /home/steve/development/play/play-2.0/framework/../repository/local/hurdy/hurdy_2.9.1/1.0-SNAPSHOT/poms/hurdy_2.9.1.pom [info] published hurdy_2.9.1 to /home/steve/development/play/play-2.0/framework/../repository/local/hurdy/hurdy_2.9.1/1.0-SNAPSHOT/jars/hurdy_2.9.1.jar [info] published hurdy_2.9.1 to /home/steve/development/play/play-2.0/framework/../repository/local/hurdy/hurdy_2.9.1/1.0-SNAPSHOT/srcs/hurdy_2.9.1-sources.jar [info] published hurdy_2.9.1 to /home/steve/development/play/play-2.0/framework/../repository/local/hurdy/hurdy_2.9.1/1.0-SNAPSHOT/docs/hurdy_2.9.1-javadoc.jar [info] published ivy to /home/steve/development/play/play-2.0/framework/../repository/local/hurdy/hurdy_2.9.1/1.0-SNAPSHOT/ivys/ivy.xml [success] Total time: 3 s, completed Apr 21, 2012 9:49:15 AMMove the published files into GitHub The files have been published to ${PLAY_HOME}/repository/local, and are contained in the hurdy directory. Move this entire directory to your new git repository cp -rv ${PLAY_HOME}/repository/local/hurdy <your username>.github.com/releasesChange directory to .github.com , and add all the files to the git repository, commit and push them. steve@hex:/tmp/schaloner.github.com$ git add . steve@hex:/tmp/schaloner.github.com$ git commit -m "Added release 1.0 to repository" steve@hex:/tmp/schaloner.github.com$ git push -u origin masterUse the dependency Create a new project (or open up an old one), and add the dependency and its location. object ApplicationBuild extends Build {val appName = "my-cool-project" val appVersion = "2.1"val appDependencies = Seq( "hurdy" %% "hurdy" % "1.0" )val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings( resolvers += Resolver.url("My GitHub Play Repository", url("http://<your username>.github.com/releases/"))(Resolver.ivyStylePatterns) ) }Note: Play has published the files in an Ivy style pattern, so this needs to be specified in your Build.scala Start Play in your application root, and run the “dependencies” task. If all goes well – and I’m sure you’ll let me know if it doesn’t – your module will be pulled from GitHub and made available to your application. Specifiying an organisation Because there’s no organisation specified in Build.scala, the organisation (repository/local/hurdy/hurdy_2.9.1) is taken to be the same as the module name. If you want an organisation, add it in the main definition: val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings( organization := "com.example" )Now, when you publish locally the files will be placed in repository/local/com.example/hurdy_2.9.1. In this case, it’s the com.example directory that should copied from the local repository to your GitHub repo. The Build.scala of any application using your dependency will be similarly different: val appDependencies = Seq( "com.example" %% "hurdy" % "1.0" )Real-world proof this works Deadbolt 2 is currently available using this mechanism, using http://schaloner.github.com as the repository. Here, there are release and snapshot versions so the Build scala of the sample applications looks like this: import sbt._ import Keys._ import PlayProject._object ApplicationBuild extends Build {val appName = "deadbolt-usage" val appVersion = "1.1.3-SNAPSHOT"val appDependencies = Seq( "be.objectify" %% "deadbolt-2" % "1.1.3-SNAPSHOT" )val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings( // Change this to point to your local play repository resolvers += Resolver.url("Objectify Play Repository", url("http://schaloner.github.com/releases/"))(Resolver.ivyStylePatterns), resolvers += Resolver.url("Objectify Play Repository", url("http://schaloner.github.com/snapshots/"))(Resolver.ivyStylePatterns) ) }If I change the required version from 1.1.3-SNAPSHOT (which is in the snapshots/ directory) to 1.1.3 (which will be in the releases/ directory), the dependency will be resolved correctly. Reference: Publishing Play 2 modules on github from our JCG partner Steve Chaloner at the Objectify blog....

The Ultimate Java Resource Collection

Hello fellow Java Geeks! Here at Java Code Geeks we are striving to create the ultimate Java to Java developers resource center. In that direction and during the past year we have made partnerships, we have set up a Java and Android tutorials page and introduced a brand new Java Examples & Code Snippets dedicated site. Last but not least we have created open source software as a reference implementation to various of our articles. But we did not stop there. We are now proud to present the ultimate Java Resource Collection on the Net! In our Resources section you will find useful resources for Java based open source projects. We categorize resources based on type. Although all of our articles include links to discussed technologies, tools and architectures, the Resources section is an index, a quick reference point for all of you who would like to get their hands right on what Java Code Geeks are working on! We hope that this effort will be a great aid to the community and we are really glad to have helped be created. Furthermore we are committed to maintain the list up to date. We would be delighted if you helped spreading the word and allowing more and more developers to come in contact with our content. Don’t forget to share! Java Resources by Java Code Geeks Happy coding everyone! Cheers, The Java Code Geeks team ...

Android Game Development with libgdx – Prototype in a day, Part 1a

In this article I will take a detour from the building blocks of a game engine and components and I will demonstrate how to prototype a game quickly using the libgdx library. What you will learn:Create a very simple 2D shooter platformer game. What a complete game architecture looks like. How to use 2D Graphics with OpenGL without knowing anything about OpenGL. What different entities make up a game and how they are tied together in a game world. How to add sound to your game. How to build your game on the desktop and deploy in onto Android – yes, it’s that magic.Steps to create a game1. Have an idea for a game. 2. Draft up some scenarios on paper to resemble your vision and how will it look like. 3. Analyse the idea, iterate over a few versions by tweaking it and decide what the game will have in its initial version. 4. Pick a technology and start prototyping. 5. Start coding and creating the assets for the game. 6. Play-test, improve, and continuously make small steps towards finishing it. 7. Polish and release!The Game Idea Because this will be a one day project, there is very limited time at disposal and the goal is to learn the technology to make games, not the actual process. For this purpose I took the liberty to borrow ideas from other games and focus on the technical aspects of this process. I will be borrowing heavily from a game called Star Guard. It’s a little gem made by Vacuum Flowers. Go get the game and check it out. A very simple shooter platformer with a simplistic style and old school arcade feel. The idea is to guide our hero through the levels by killing enemies and and dodging everything that tries to kill us. The controls are simple, the arrow keys move the hero to the left or right, Z jumps and X shoots the laser. The longer the jump button is held, the higher the hero jumps. He can change direction in the air and also shoot. We’ll see how we can translate these controls to Android later on. The next steps (2 and 3) can be skipped over as we will already have this taken care of because of the functioning game. Start your Eclipse This is where we start. I will be using libgdx library to create the game. Why libgdx? It’s the best library (in my opinion) that makes developing games easy without knowing much about the underlying technology. It allows developers to create their games on the desktop and deploy it to Android without any modification. It offers all the elements to use it in games and hides the complexity of dealing with specific technologies and hardware. It will become more obvious as we go along. Setting up the project By following the instructions from libgdx’s documentation we have to first download the library. Go to http://libgdx.badlogicgames.com/nightlies/ and download the libgdx-nightly-latest.zip file and unpack it. Create a simple java project in eclipse. I will call it star-assault.Leave the default settings and once the project was created, right click on it and select New->Folder and create a directory named libs. From the unpacked libgdx-nighly-latest directory, copy the gdx.jar file into the newly created libs directory. Also copy the the gdx-sources.jar file into the libs directory. It is in the sources sub-directory of the unpacked gdx directory. You can do this by simply dragging the jar files into your directories in eclipse. If you copy them using explorer, or finder or any other means, don’t forget to refresh your eclipse project after by pressing F5. The structure should look like the following image:Add gdx.jar as a dependency to the project. Do this by right-clicking the project title and select Properties. On this screen pick Java Build Path and click onto the Libraries tab. Click Add JARs…, navigate to the libs directory and select gdx.jar, then click OK. In order to have access to the gdx source code and to be able to debug our game easily, it’s a good idea to add the sources to the gdx.jar file. To do this, expand the gdx.jar node, select Source attachment, click Edit…, then Workspace… and pick gdx-sources.jar then OK until all the pop-up windows are closed.The complete documentation for setting up projects with libgdx can be found on the official wiki. This project will be the core project for the game. It will contain the game mechanics, the engine, everything. We will need to create two more projects, basically launchers for the 2 platforms we are targeting. One for Android and one for Desktop. These projects will be extremely simple and will contain only the dependencies required to run the game on the respective platforms. Think of them as the class containing the main method. Why do we need separate projects for these? Because libgdx hides the complexity of dealing with the underlying operating system (graphics, audio, user input, file i/o, etc.), Each platform has a specific implementation and we will need to include only those implementations (bindings) that are required targeted. Also because the application life-cycle, the asset loading (loading of images, sounds, etc) and other common aspects of an application are heavily simplified, the platform specific implementations reside in different JAR files and only those need to be included that are required for the platform we are targeting. The Desktop Version Create a simple java project as in the previous step and name it star-assault-desktop. Also follow the steps to create the libs directory. This time the required jar files from the downloaded zip file are: gdx-natives.jar, gdx-backend-lwjgl.jar, gdx-backend-lwjgl-natives.jar. Also add these jar files as dependencies to the project as in the previous project. (right click the project -> Properties -> Java Build Path -> Libraries -> Add JARs, select the three JARs and click OK.) We also need to add the star-assault project to the dependencies. To do this, click the Projects tab, click Add, check the star-assault project and click OK. Important! We need to make the star-assault project a transitive dependency, meaning that dependencies for this project to be made dependencies of projects depending on this. To do this: right click on the main project -> Properties -> Java Build Path -> Order and Export -> check the gdx.jar file and click OK. The Android Version For this you will need the Android SDK installed. Create a new Android project in eclipse: File -> New -> Project -> Android Project. Name it star-assault-android. For build target, check “Android 2.3?. Specify a package name net.obviam or your own preference. Next to “Create Activity” enter StarAssaultActivity. Click Finish.Go to the project directory and create a sub-directory named libs (you can do this from eclipse). From the nightly zip, place gdx-backend-android.jar and the armeabi and armeabi-v7a directories in the newly created libs directory. In eclipse, right click the project -> Properties -> Java Build Path -> Libraries -> Add JARs, select gdx-backend-android.jar and click OK. Click Add JARs again, select gdx.jar under the main project (star-assault) and click OK. Click the Projects tab, click Add, check the main project and click OK twice. This is how the structure should look like:Important! For ADT release 17 and newer, the gdx jar files need to be explicitly marked to be exported. To do this Click on the Android Project Select Properties Select Java Build Path (step 1) Select Order and Export (step 2) Check all the references, e.g. the gdx.jar, the gdx-backend-android.jar, the main project etc. (step 3). The following image shows the new state.Also, more information on this issue here. Sharing the Assets (images, sounds and other data) Because the game will be identical on both desktop and Android but each version requires to be built separately from different projects, we want to keep the images, sounds and other data files in a shared location. Ideally this would be in the main project as it is included in both Android and desktop bu because Android has a strict rule on where to keep all these files, we will have to keep the assets there. It is in the automatically created assets directory in the Android project. In eclipse there is the possibility to link directories as in symbolic links on linux/mac or shortcuts in windows. To link the assets directory from the Android project to the desktop project do the following: Right click the star-assault-desktop project -> Properties -> Java Build Path -> Source tab -> Link Source… -> Browse… -> browse to the asssets directory in the star-assault-android project and click Finish. You can also extend the Variables… instead of browsing to the assets directory. It is recommended as it makes the project file system independent. Also make sure the assets directory is included as a source folder. To do that, right click on the assets directory in eclipse (the desktop project), select Build Path -> Use as Source Folder. At this stage we are ready with the setup and we can go ahead to work on the game. Creating the Game A computer application is a piece of software that runs on a machine. It starts up, does something (even if that’s nothing) and stops in a way or another. A computer game is a specific type of application in which the “does something” part is filled with a game. The start and end is common to all applications. Also the game has a very straight forward architecture based around an continuous loop. You can find out more about the architecture and the loop here and here. Thanks to libgdx our game can be pieced together as a staged play in a theatre. All you need to do is, to think of the game as a theatrical play. We will define the stages, the actors, their roles and behaviours, but we will delegate the choreography to the player. So to set up our game/play we need to take the following steps:1. Start application. 2. Load up all the images and sounds and store them in memory. 3. Create the stages for our play along with the actors and their behaviours (rules for interactions between them). 4. Hand the control to the player. 5. Create the engine that will manipulate the actors on the stage based on the input received from the controller. 6. Determine when the play ends. 7. End the show.It looks quite simple and it really is. I will be introducing the notions and elements as they appear. To create the Game we simply need just one class. Let’s create StarAssault.java in the star-assault project. Every class will be created in this project with 2 exceptions. package net.obviam.starassault;import com.badlogic.gdx.ApplicationListener;public class StarAssault implements ApplicationListener {@Override public void create() { // TODO Auto-generated method stub }@Override public void resize(int width, int height) { // TODO Auto-generated method stub }@Override public void render() { // TODO Auto-generated method stub }@Override public void pause() { // TODO Auto-generated method stub }@Override public void resume() { // TODO Auto-generated method stub }@Override public void dispose() { // TODO Auto-generated method stub } }Just implement ApplicationListener from gdx and eclipse will generate the stubs for the methods needed to be implemented. These are all the methods that we need to implement from the application lifecycle. It is very simple considering all the setup code needed for Android, or on desktop to initialise the OpenGL context and all those boring (and difficult) tasks. The method create() is called first. This happens when the application is ready and we can start loading our assets and create the stage and actors. Think of building the stage for the play in a theatre AFTER all the things have been shipped there and prepared. Depending on where the theatre is and how you get there, the logistic can be a nightmare. You can ship things by hand, or by plane or trucks…we don’t know. We’re inside and have the stuff ready and we can start to assemble it. This is what libgdx is doing for us. Shipping our stuff and delivering it regardless of the platform. The method resize(int width, int height) is called every time the drawable surface is resized. This gives us the chance to rearrange the bits before we go on to start the play. It happens when the window (if the game runs in one) is resized for example. The heart of every game is the render() method which is nothing more than the infinite loop. This gets called continuously until we decide that the game is over and want to terminate the program. This is the play in progress. Note: For computers the game over is not equivalent of program over. So it’s just a state. The program is in a state of game over, but is still running. Of course that the play can be interrupted bu pauses and they can be resumed. The pause() method will be called whenever the application enters into the background on the desktop or Android. When the application comes to the foreground it resumes and the resume() method is being called. When the game is done and the application is being closed, the dispose() is called and this is the time to do some cleanup. It’s similar when the play is over, spectators have left and the stage is being dismantled. No more coming back. More on the lifecycle here. The Actors Let’s start taking steps towards the actual game. The first mile-stone is to have a world in which our guy can move. The world is composed of levels and each level is composed of a terrain. The terrain is nothing more than some blocks through which our guy can’t go. Identifying the actors and entities so far in the game is easy. We have the guy (let’s call him Bob – libgdx has tutorials with Bob) and the blocks that make up the world. Having played Star Guard we can see that Bob has a few states. When we don’t touch anything, Bob is idle. He can also move (in both directions) and he can also jump. Also when he’s dead, he can’t do anything. Bob can be in only one of the 4 identified states at any given time. There are other states as well but we’ll leave them out for now. The states for Bob:Idle – when not moving or jumping and is alive Moving – either left or right at a constant speed. Jumping – also facing left or right and high or low. Dead – he’s not even visible and respawning.The Blocks are the other actors. For simplicity we have just blocks. The level consists of blocks placed in a 2 dimensional space. For simplicity we will use a grid. Turn the start of Star Guard into a block and Bob structure, will look something like this:The top one is the original and the bottom one is our world representation. We have imagined the world but we need to work in a measure system that we can make sense of. For simplicity we will say that one block in the world is one unit wide and 1 unit tall. We can use meters to make it even simpler but because Bob is half a unit, it makes him half a meter. Let’s say 4 units in the game world make up 1 meter so Bob will be 2 meters tall.It is important because when we will calculate the speed with which Bob runs for example, we need to know what we’re doing. Let’s create the world. Our main playable character is Bob. The Bob.java class looks like this: package net.obviam.starassault.model;import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2;public class Bob {public enum State { IDLE, WALKING, JUMPING, DYING }static final float SPEED = 2f; // unit per second static final float JUMP_VELOCITY = 1f; static final float SIZE = 0.5f; // half a unitVector2 position = new Vector2(); Vector2 acceleration = new Vector2(); Vector2 velocity = new Vector2(); Rectangle bounds = new Rectangle(); State state = State.IDLE; boolean facingLeft = true;public Bob(Vector2 position) { this.position = position; this.bounds.height = SIZE; this.bounds.width = SIZE; } }Lines #16-#21 define the attributes of Bob. The values of these attributes define Bob’s state at any given time. position – Bob’s position in the world. This is expressed in world coordinates (more on this later). acceleration – This will determine the acceleration when Bob jumps. velocity – Will be calculated and used for moving Bob around. bounds – Each element in the game will have a bounding box. This is nothing more than a rectangle, in order to know if Bob ran into a wall, got killed by a bullet or shot an enemy and hit. It will be used for collision detection. Think of playing with cubes. state – the current state of Bob. When we issue the walk action, the state will be WALKING and based on this state, we know what to draw onto the screen. facingLeft – represents Bob’s bearing. Being a simple 2D platformer, we have just 2 facings. Left and right. Lines #12-#15 define some constants we will use to calculate the speed and positions in the world. These will be tweaked later on. We also need some blocks to make up the world. The Block.java class looks like this: package net.obviam.starassault.model;import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2;public class Block {static final float SIZE = 1f;Vector2 position = new Vector2(); Rectangle bounds = new Rectangle();public Block(Vector2 pos) { this.position = pos; this.bounds.width = SIZE; this.bounds.height = SIZE; } }Blocks are nothing more than rectangles placed in the world. We will use these blocks to make up the terrain. We have one simple rule. Nothing can penetrate them. libgdx note You might have noticed that we are using the Vector2 type from libgdx. This makes our life considerably easier as it provides everything we need to work with Euclidean vectors. We will use vectors to position entities, to calculate speeds, and to move thing around. About the coordinate system and units As the real world, our world has dimensions. Think of a room in a flat. It has a width, height and depth. We will make it 2 dimensional and will get rid of the depth. If the room is 5 meters wide and 3 meters tall we can say that we described the room in the metric system. It is easy to imagine placing a table 1 meter wide and 1 meter tall in the middle. We can’t go through the table, to cross it, we will need to jump on top of it, walk 1 meter and jump off. We can use multiple tables to create a pyramid and create some weird designs in the room. In our star assault world, the world represents the room, the blocks the table and the unit, the meter in the real world. If I run with 10km/h that translates to 2.77777778 metres / second ( 10 * 1000 / 3600). To translate this to Star Assault world coordinates, we will say that to resemble a 10km/h speed, we will use 2.7 units/second. Examine the following diagram of representing the bounding boxes and Bob in the world coordinate system.The red squares are the bounding boxes of the blocks. The green square is Bob’s bounding box. The empty squares are just empty air. The grid is just for reference. This is the world we will be creating our simulations in. The coordinate system’s origin is at the bottom left, so walking left at 10.000 units/hour means that Bob’s position’s X coordinate will decrease with 2.7 units every second. Also note that the access to the members is package default and the models are in a separate package. We will have to create accessor methods (getters and setters) to get access to them from the engine. Creating the World As a first step we will just create the world as a hard-coded tiny room. It will be 10 units wide and 7 units tall. We will place Bob and the blocks following the image shown below.The World.java looks like this: package net.obviam.starassault.model;import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array;public class World {/** The blocks making up the world **/ Array<Block> blocks = new Array<Block>(); /** Our player controlled hero **/ Bob bob;// Getters ----------- public Array<Block> getBlocks() { return blocks; } public Bob getBob() { return bob; } // --------------------public World() { createDemoWorld(); }private void createDemoWorld() { bob = new Bob(new Vector2(7, 2));for (int i = 0; i < 10; i++) { blocks.add(new Block(new Vector2(i, 0))); blocks.add(new Block(new Vector2(i, 7))); if (i > 2) blocks.add(new Block(new Vector2(i, 1))); } blocks.add(new Block(new Vector2(9, 2))); blocks.add(new Block(new Vector2(9, 3))); blocks.add(new Block(new Vector2(9, 4))); blocks.add(new Block(new Vector2(9, 5)));blocks.add(new Block(new Vector2(6, 3))); blocks.add(new Block(new Vector2(6, 4))); blocks.add(new Block(new Vector2(6, 5))); } }It is a simple container class for the entities in the world. Currently the entities are the blocks and Bob. In the constructor the blocks are added to the blocks array and Bob is created. It’s all hard-coded for the time being. Remember that the origin is in the bottom left corner. Check out the rest of the tutorial here. Reference: Getting Started in Android Game Development with libgdx – Create a Working Prototype in a Day – Tutorial Part 1 from our JCG partner Impaler at the Against the Grain 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: