Featured FREE Whitepapers

What's New Here?

software-development-2-logo

Application Performance and Antipatterns

Any application you pick up, there are some issues – big or small. There will be copy-paste code, mistakes, algorithms which could have better thought through. But what distinguishes an antipattern from these normal errors is that like patterns these antipatterns are recurring throughout the code base. In my recent experience in dealing with performance issues, I had observed certain recurrent themes that are undermining the overall application performance. Most of these antipatterns are well documented but it seems we do not learn from others mistakes. We need to make our own mistakes. I am recounting some of the common patterns that I observed in the recent months.Excessive Layering – Most of the underlying performance starts with the excessive layering antipattern. The application design has grown over the usage of controllers, commands and facades. In order to decouple each layer, the designers are adding facades at each of the tiers. Now, for every request at the web tier, the request call goes through multiple layers just to fetch the results. Imagine doing this for thousands of requests coming in and the load the JVM need to handle to process these requests. The number of objects that get created and destroyed when making these calls add to the memory overhead. This further limits the amount of requests that can be handled by each server node. Based on the size of the application, deployment model, the number of user’s, appropriate decision need to be taken to reduce the number of layers. E.g. if the entire application gets deployed in the same container, there is no need to create multiple layers of process beans, service beans(business beans), data access objects etc. Similarly, when developing an internet scale application, large number of layers start adding overheads to the request processing. Remember, large number of layers means large number of classes which effectively start impacting the overall application maintainability.Round Tripping- With the advent of ORM mappings, Session/DAO objects, the programmer starts making calls to beans for every data. This leading to excessive calls between the layers. Another side issue is the number of method calls each layer start having to support this model. Worse case is, when the beans are web service based. Client tier making multiple web service calls within a single user request have a direct impact on the application performance. To reduce the round tripping, the application needs to handle or combine multiple requests at the business tier.Overstuffed Session- Session object is a feature provided by the JEE container to track user session during the web site visit. The application start with the promise of putting very minimal information in the session but over a period of time, the session object keeps on growing. Too much of data or wrong kind of data is stuffed into the session object. Large data objects will mean that the objects placed in the session will linger on till the session object is destroyed. This impacts the number of user’s that can be served by the application server node. Further, I have seen, application using session clustering to support availability requirements but adding significant overheads to the network traffic and ability of application to handle higher number of users. To unstuff the session object, take an inventory of what all goes there, see what is necessary, what objects can be defaulted to request scope. For others, remove the objects from session when their usage is over.Golden Hammer (Everything is a Service) – With the advent of SOA, there is tendency to expose the business services, which can be orchestrated into process services. In the older applications, one can observe similar pattern being implemented with EJBs. This pattern coupled with the bottom up design approach at times, means exposing each and every data entity as a business service. This kind of design might be working correctly functionally, but from the performance and maintenance point of view, it soon becomes a night mare. Every web service call adds overhead in terms of data serialization and deserialization. At times, the data(XML) being passed with web service calls is also huge leading to performance issues. The usage of services or ejb’s should to be evaluated from application usage perspective. Attention needs to be paid on the contract design.Chatty Services – Another pattern observed is the way the service is implemented via multiple web service calls each of which is communicating a small piece of data. This results in explosion of web services and which leads to degradation of performance and unmaintainable code. Also, from the deployment perspective, the application starts running into problems. I have come across projects which have hundred plus services all getting crammed into a single deployment unit. When the application comes up, the base heap requirement is already in 2Gb range leaving not much space for application to run. If the application is having too many fine grained services, then it an indication towards the application of this antipattern.The above mentioned antipatterns are frequent causes of application performance issues. The teams usually start with the right intentions but over a period of time, things will start slipping. Some of the common reasonsLack of design standards and reviews processes – even if these exists, the delivery pressure is leading to skipping these processes Team members inexperience or narrow view leads to every programmer only looking at their module and nobody is looking at the overall application performance Continuous Integration(CI) tools not integrated with compliance check tools like PMD, Checkstyle, FindBugs etc No focus on profiling of the application on regular basis during the code construction phase Not evaluating the results from the Load tests to decipher and fix the underlying issue (blaming the poor infrastructure setup)What are the other antipatterns you have observed that have contributed to the degradation in the application performance. Do share! Reference: Application Performance and Antipatterns from our JCG partner Munish K Gupta at the Tech Spot blog....
software-development-2-logo

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....
software-development-2-logo

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....
software-development-2-logo

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....
apache-camel-logo

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....
google-gwt-logo

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

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

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

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

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

Subscribe to our newsletter to start Rocking right now!

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

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