Featured FREE Whitepapers

What's New Here?

akka-logo

Maven Web Project Kickstarter Codebase with Spring, Hibernate, Akka, Twitter Bootstrap, Apache Tiles and jQuery

I am happy to upload my second project to GitHub to help people get started with Java Web App Development as quickly as possible. I am sharing this code with Apache License 2.0. Here is the URL for the same: https://github.com/ykameshrao/spring-hibernate-springdata-springmvc-maven-project-framework The project consists of following parts: 1) Commons-Deps: Dependencies declared as a single pom file to easily manage the project dependencies. It is upto personal choice of users to still continue have it this way or go with their own chosen method to manage dependencies in maven pom. 2) Commons: A lot of common code snippets are provided as part of commons jar module to help send mails using gmail, java mail, utf8 encoding, JCS cache managers, session managers, random string, etc. 3) Framework: This part of the code base includes JPA and Spring Data Entities, JPA and Spring Data Repositories, Services which are built using Java Generics to help provide the CRUD actions on these Entities when users build their own domain specific entities, repositories and services extending the ones provided here. It also contains, API and Web App Controllers providing basic functionality again for people interested in building their own Spring MVC controllers using these. Also, contained here are validators, exceptions, AOP based exception handlers. 4) Your Own Web App Code: This part of the code provides a bootstrapped web project with API and Web UI using the best practices I picked across time to do things using the third party frameworks, libraries I have chosen here. The API parts is configured to accept and generate both XML and JSON request and response formats. Akka is also configured here to present the method in which it can be used to offload activities from your Spring MVC controllers (Servlets). Here it is programmed to offload the task of sending emails. This is the wrapper framework laid out to start building Spring based Web apps with Hibernate ORM layer or Spring Data ORM powered NoSQL and Spring MVC in Java programming language. The purpose of this project is to get you started quickly in Java web app development over a widely used and tested Java web development infrastructure. This project provides sample hibernate entities, spring data entities, akka actors to offload mail sending like jobs, models, repositories, services and controllers classes. There are also many framework level classes to help handle exceptions and errors in the project you may start developing using this. The UI for the default simple web project bundled in this framework is built using Twiiter Bootstrap, Apache Tiles, jQuery, jQuery Validation, JSPs. I can try my best to provide with as much detail as possible here, but the best way to understand all that is provided is by reading the code. Therefore, I also provided a sample web app project with functionality to register and login a user. All the code is presented in a package structure that can be renamed as per your own choice and requirements. Enjoy! Configurations config/props/mail.properties mail.transport.protocol=smtps mail.host=smtp.gmail.com mail.user= mail.pass= mail.port=465 mail.starttls=true mail.auth=true mail.debug=true mail.fromAddress=config/props/database.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/yourwebprojectdb jdbc.username= jdbc.password= hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=600 hibernate.c3p0.max_statements=50src/main/resources/tiles/templates.web.xml <?xml version=”1.0” encoding=”UTF-8” ?> <!DOCTYPE tiles-definitions PUBLIC ”-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN” ”http://tiles.apache.org/dtds/tiles-config_2_0.dtd”> <tiles-definitions> <definition name=”base” template=”/WEB-INF/views/layout/web.jsp”> <put-attribute name=”title” value=”” /> <put-attribute name=”header” value=”/WEB-INF/views/common/header.web.jsp” /> <put-attribute name=”message” value=”/WEB-INF/views/common/message.web.jsp” /> <put-attribute name=”content” value=”” /> <put-attribute name=”footer” value=”/WEB-INF/views/common/footer.web.jsp” /> </definition> <definition name=”home” extends=”base”> <put-attribute name=”title” value=”Your Web Project” /> <put-attribute name=”content” value=”/WEB-INF/views/web/home.web.jsp” /> </definition> <definition name=”userRegistration” extends=”base”> <put-attribute name=”title” value=”Register” /> <put-attribute name=”content” value=”/WEB-INF/views/web/userRegistration.web.jsp” /> </definition> <definition name=”dashboard” extends=”base”> <put-attribute name=”title” value=”Dashboard” /> <put-attribute name=”content” value=”/WEB-INF/views/web/dashboard.web.jsp” /> </definition> <definition name=”error” extends=”base”> <put-attribute name=”title” value=”Error” /> <put-attribute name=”content” value=”/WEB-INF/views/web/error.web.jsp” /> </definition> </tiles-definitions>Startup VM Options Required -Dconf.path=”path-to-config-folder-on-target-machine-containing-property-files”Refer: src/main/resources/config/spring/applicationContext-properties.xml <util:properties id=”mdbProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/mongodb.properties” /> <util:properties id=”dbProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/database.properties” /> <util:properties id=”logProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/log4j.properties” /> <util:properties id=”amProps” location=”file:#{systemProperties[‘conf.path’]}/config/props/api.messages.properties” />:: Screenshots  The frameworks strung together supporting multiple activities in this framework layer of code are -  Maven Java 1.7  Spring 3.1.1  Hibernate 4+  Spring Data  MongoDB  Akka 1.3+  Apache Tiles 2+  Twitter Bootstrap 2+  Velocity for Mails  BootSwatch  jQuery Reference: Spring, Hibernate, Spring Data, Akka, Twitter Bootstrap, Apache Tiles, jQuery powered Maven Java Web Project Kickstarter Codebase from our JCG partner Y Kamesh Rao at the OrangeApple blog. ...
javaone-logo

JavaOne 2012: Difficult Decisions

It was recently announced that the JavaOne 2012 Schedule Builder is now available. I have signed up for my first cut at sessions that I will attend, but found myself experiencing the typical feelings of excitement and disappointment as I did so.If I was forced to make a Top Ten list of the sessions I have been most interested in attending at JavaOne 2012, I would estimate that 3 to 4 of those are being offered at exactly the same time and there are a couple others in conflict with one another. On one hand, I find myself excited at the idea of attending certain presentations, but this is tempered at the disappointment realized when I see other presentations at the same time that I’ll have to miss. There is undoubtedly an opportunity cost associated with seeing my chosen presentations.One of the session slots that is most difficult for me to make a final decision regarding is the Monday (October 1) 10 am session. In that session, I must choose between “The Road to Lambda” (CON4862), “Concurrency without Pain in Pure Java” (CON3454), “Finding and Solving Java Deadlocks” (HOL6500), “Efficient Memory and Thread Management in Highly Parallel Applications” (CON4611), “Uncovering Hidden Power Tools in the JDK” (CON7059), “JSR 311: Constraint Programming API” (CON3255), “Lessons Learned: Use of Modern JVM Languages Besides Java” (CON2424), “Effective HATEOAS with JAX-RS” (CON3383), “How RESTful is Your REST?” (CON7573), “Make Your Clients Richer: JavaFX and the NetBeans Platform” (TUT4801), “Building Amazing Applications with JavaFX” (CON4606), and several other interesting sounding presentations. I’m currently leaning toward “The Road to Lambda” because I believe lambda expressions will “change everything” in how we think about and write Java and because Brian Goetz is its presenter.Another example of being forced to make a very difficult decision is the 8:30 am slot on Tuesday (October 2). Among other great sessions, I am forced to choose between “Lambda: A Peek Under the Hood” (CON6080), “Introduction to the Play Framework” (CON3845), “Modern Software Development Antipatterns” (CON6152), “Kotlin: Practical Aspects of JVM Language Implementation” (CON5759), “The Evolution of Java Persistence” (CON6622), “New Image Operations in JavaFX” (CON4440), and “3-D Made Easy with JavaFX” (CON4513).A final example that I’ll cover here of the difficult decisions to be made comes from the 10 am hour on Wednesday (October 3). Among many great sessions available in that hour, I am having an especially difficult time making my mind up between “Unlocking the Java EE 6 Platform” (CON2987), “Innovating Testing Techniques with Bytecode Instrumentation” (CON3961), “Software Modularity: Paradoxes, Principles, and Architectures” (CON3992), “Design Patterns in Modern JVM Languages” (CON3455), “Developing Polygot Persistence Applications” (CON4775), “JSR 353: Java API for JSON Processing” (CON3566), “Audio and Video Processing in JavaFX” (CON7146), “Do It Yourself: Custom JavaFX Controls” (CON2425), and “Building HTML5 Mobile Apps with Cloud Services” (CON11114). Fortunately, I don’t have this same hour’s Are Your Garbage Collection Logs Speaking to You on this difficult choices list because I attended it last year.I listed a session code after each session name in the lists above. The session naming uses the following convention:BOF – Birds-Of-a-Feather CON – Conference Session HOL – Hands-On Lab KEY – Keynote Speech TSF – Test Fest TUT – Tutorial UGF – User Group ForumI focused on three hours of JavaOne 2012 that provide a set of presentations of such great interest that it is difficult to choose only one from the group. Although I used three for examples here, the truth is that just about every hour had at least two of my “must see” presentations and many had more than two in the same hour.Even though I’ve made initial selections for which presentations I plan to attend, these will change between now and the conference and even during the conference. In fact, they already have changed some since the Content Catalog was released. In particular, my previously high level of interest in Mark Reinhold‘s “The Modular Java Platform and Project Jigsaw” (CON10844) is lessened significantly since learning that it is likely that we won’t see Project Jigsaw until at least 2015 (Java 9). It is difficult to justify using a precious time slot on something that we likely won’t see for at least 3 more years.As I was browsing through the JavaOne 2012 presentations and the Oracle OpenWorld 2012 presentations, I noted that no JavaOne session had yet filled up, but several Oracle OpenWorld sessions are already full. I like that Schedule Builder tells you that it’s full and tells you how many people are already on the waiting list. In one case, an Oracle OpenWorld session already had a waiting list of 43 people!One of the things I don’t like about Schedule Builder is that some of the pre-selected sessions that appeared on “My Schedule” keep reappearing every time I log into Schedule Builder even though I explicitly remove them every time I’m in the tool. I’ve stopped removing them for now, but would like to have them permanently removed so that it is more clear what I have scheduled each day.I am trying to attend presentations representing a wide variety of topics at JavaOne 2012. I could attend a presentation on JavaFX in just about every session, but I hope to cover a much broader set of topics than just JavaFX. I’m trying to mix in some JavaFX, basic Java SE tooling, alternative JVM languages, and more. The biggest challenge is eliminating so many great sessions and trying to live with attending just one each hour.Reference: JavaOne 2012: Difficult Decisions from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
agile-logo

Does the PMI-ACP set the bar high enough on Risk Management?

I’m trying to understand the PMI’s new certification for Agile Certified Practitioners, and what value the PMI brings to managing software development projects using Agile methods. So I bought RMC’s PMI-ACP Exam Prep Guide which is written by Mike Griffiths, a guy who understands a lot about project management and Agile methods, and who has been heavily involved in the PMI-ACP program. How PMI-ACP looks at Risk I started with how the PMI says risk management should be done in Agile projects. Unlike the PMBOK, the PMI-ACP does not treat risk management as a knowledge area. Instead, it integrates risk into the different practice domains and activities in Agile projects, from prioritization to delivery and problem management. The first mention of risk management is in “Value-Driven Delivery”, treating risks as “anti-value” when considering what is important to the customer and the business. Fair enough. Later in the same section there is a discussion of how risks need to be considered when managing the backlog – that you should schedule risk avoidance and risk mitigation activities early in the project, and explaining how to rank work by business value and risk. They suggest leveling the playing field by ranking all work (new features and changes and risks) by financial value, expressing everything in monetary terms. Risks have a negative financial return: risk impact in $ x risk probability in %. This only applies to risks that have avoidance / mitigation activities that can be scheduled and costed in the project – not for risks that are accepted or transferred. I like the approach of managing risks the same as any other work, using the same costing and prioritization approach. It’s more consistent and more actionable than managing risks from separate lists. Risk Management comes up one more time in Value-Driven Delivery, under a discussion of reporting tools and techniques, in this case how to create and use Risk Burn Down reports. Then risk comes up again in Adaptive Planning – which makes sense. Risk assessment, like everything else in planning an Agile project, needs to be done incrementally and iteratively. But unfortunately there’s not a lot on how teams are supposed to identify risks in planning. Later Griffiths suggests a collaborative game called Speedboat or Sailboat, to help the team come up with a list of risks and opportunities. This is Agile, so everything including risk management needs to be fun, and we don’t want to get people bummed out, so it’s important to spend time identifying opportunities too upfront. Team members post anchor (risk) and wind (opportunity) sticky notes around the picture of a boat on the water. Isn’t that nice… Griffith does say that “For any project, we should engage the development team, sponsors, customers, and other relevant stakeholders in the process of risk identification. Their ideas, along with reviews of previous projects’ lessons learned lists, risk logs and industry risk profiles, should be used to identify the known and likely risks for the project.” But you can only use “lessons learned lists” and “risk logs” from previous projects if somebody on the previous project created them – and there are no actions in the PMI-ACP description of risk management to make sure that this gets done. As part of Continuous Improvement, Agile teams do conduct lessons learned reviews in each iteration, rather than waiting until the end of the project (a step that is often skipped because time and money have run out). The point is to act on lessons learned information immediately – not maybe on some other project in the future. This is good, but if people don’t save information for future use, then you can’t talk about using it in the future. The last reference to risk management is under Problem Detection and Resolution – recommending running risk-based spikes early in the project to assess technical risks. Emphasizing that it is better to find out and fail early if you run into technical problems or limitations.Is integrated and implicit risk management enough? The PMI-ACP emphasizes integrated and active risk management as part of incremental planning and delivery. “Risk management should serve as a driver for work scheduling, moving high-risk activities into earlier iterations of the project and incorporating risk mitigation activities into the backlog.” Because risk-management activities are treated the same as other backlog items, work is always being done on reducing or containing risk based on negative value. But because risk management is built-in to different practice domains and into different tools and techniques, there’s no one place to understand how risk management should be done in an Agile project, and to assess whether it is being done well or not. You need to look at each practice area and how risk applies in each context. The way that it is organized makes it difficult to get your head around how risk management should be done in an Agile way – which is a source of risk in itself. My criticisms aren’t of the study guide, which is well-written. They are of the PMI and the PMI-ACP framework. The PMI-ACP does put more emphasis on risk management than other descriptions of Agile development that I have seen so far. But it’s disappointing that the PMI did not take the opportunity to shore up a fundamental weakness in the Agile approach to development and recommend making risk management explicit, adding risk management activities to planning and reviews as a standard practice. Some of these ideas are described in the Software Project Manager’s Bridge to Agility, a book that maps Agile development to PMI’s project management framework, and one of the books referenced in the PMI-ACP. But in the PMI-ACP as it is described, like most Agile development today, there’s too much reliance on the kind of risk management that comes for free in iterative and incremental development. This is probably enough for small teams working on simple application development projects, but that’s not the audience for PMI certification. Anyone using Agile methods on a larger scale or in high-risk development will need to look someplace else for help. Reference: Does the PMI-ACP set the bar high enough on Risk Management? from our JCG partner Jim Bird at the Building Real Software blog....
enterprise-java-logo

Getting started with JAX-WS

JAX-WS stands for Java API for XML Web Services. It is a Java programming language API for creating web services and clients that communicate using XML. This post is a quick start for JAX-WS. PrerequisitesGlassFish integrated with Eclipse. Creating the JAX-WS Web Service 1.In Eclipse create a Dynamic Web Project called ‘com.eviac.blog.jaxwsproj’. Make GlassFish as the Target Runtime.           2.Create a new class called ‘SampleWS’ in the created project. This will be the implementation class of the web service.SampleWS.java package com.eviac.blog.jaxws.service;import javax.jws.WebMethod; import javax.jws.WebService;@WebService public class SampleWS {@WebMethod public int sum(int a, int b) { return a + b; }@WebMethod public int multiply(int a, int b) { return a * b; }}3.Open a terminal and navigate to the root of the project directory. Create a directory called wsdl inside WebContent/WEB-INF/. Use the following command to create web service artifacts. Make sure your JAVA_ HOME is set properly or this command will not work. Also make sure to build the project before running this command or it will complain class not found. wsgen -classpath build/classes/ -wsdl -r WebContent/WEB-INF/wsdl -s src -d build/classes/ com.eviac.blog.jaxws.service.SampleWS4.Refresh the project to discover created artifacts. Open the created WSDL-file inside wsdl folder. Search for REPLACE_WITH_ACTUAL_URL and replace it with the web service URL: http://localhost:8080/com.eviac.blog.jaxwsproj/SampleWSService, and save the file.5.Deploy the project in Glassfish by right-clicking the project, click Run As -> Run on Server and select the Glassfish server.Creating the JAX-WS client 1.Create a Java project in eclipse called ‘com.eviac.blog.jaxwsclientproj’. Open up a new terminal and go to the project root. Use the following command to generate the classes you need to access the web service. Here you will need to use the URL of the WSDL file. wsimport -s src -d bin http://localhost:8080/com.eviac.blog.jaxwsproj/SampleWSService?wsdl2.Create a new class called ‘SampleWSClient’ in the project.SampleWSClient.java package com.eviac.blog.jaxws.client;import javax.xml.ws.WebServiceRef;import com.eviac.blog.jaxws.service.SampleWS; import com.eviac.blog.jaxws.service.SampleWSService;public class SampleWSClient {@WebServiceRef(wsdlLocation = 'http://localhost:8080/com.eviac.blog.jaxwsproj/SampleWSService?wsdl') private static SampleWSService Samplews;public static void main(String[] args) { SampleWSClient wsClient = new SampleWSClient(); wsClient.run(); }public void run() { Samplews = new SampleWSService(); SampleWS port = Samplews.getSampleWSPort(); System.out.println('multiplication Result= '+ port.multiply(10, 20)); System.out.println('Addition Result= '+port.sum(10, 20)); }}3.Right click on the project and click on Run As -> Java Application. This will result following. multiplication Result= 200 Addition Result= 30Reference: Getting started with JAX-WS from our JCG partner Pavithra Siriwardena at the EVIAC blog....
apache-camel-logo

Apache Camel using Groovy Introduction

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

Application Scalability: Still elusive for Enterprises Apps

The advent of the Consumer Business application like Facebook, Twitter has changed the definition of Application Scalability. Decade back 10 million+ was a large user base, Facebook will touch 1Billion+ users by end of this year. There are hordes of applications in 100+ million user range. The techniques and approaches employed by these large Consumer Business Applications are different from the traditional enterprise application design and architecture techniques.If we study the architectures principles employed by these large Consumer Business Applications, then we can conclude to the followingAll the large consumer business applications are build and make use of Cloud Computing Applications are build using a combination of open source products and platforms Create solutions where the current set of solution do not meet requirement or scale up (e.g. HipHop, Hadoop, ChaosMonkey etc) Constant knowledge sharing within the community (FB/Twitter/Google open sources lot of their internal products)From the Application scalability perspective, the following key architecture patterns have emerged that are being used to scale the applicationStateless Applications – Modern Web applications maintain state, which means that they remember what you were did as part of your last request, and they remember all this data as part of the Session. The Stateful nature of the application means if the server holding that state goes down, the entire user state is lost. Traditional techniques like sync user session data across server nodes or persisting in data store do not scale very well. To overcome this shortcoming, the whole concept of creating stateless applications where the servers do not maintain state. The application uses cookies and makes use of RESTful API’s to craft the user experience. Newer frameworks like Play Framework, Node.js, Vertx.io all promote this stateless application development that scales with the increasing user load very well. Another option used is to offload session state is high throughput memory based key value store, which is common across stateless nodes. Data Sharding – Another issue encountered with scale is the increasing load on DB servers. DB Servers do employ techniques like Master/Slave or Clustering techniques coupled with large powerful boxes but beyond 100+ million users, these techniques also fail. Further, the costly hardware and software licenses make the traditional DB options very costly. So, companies have used the MySQL as the base and created lots of solutions/topologies around the same. One of those techniques is data sharding. A Data shard is a horizontal partition of the data, meaning rows of the tables are held separately. There are numerous advantages to this partitioning approach. Since the tables are divided and distributed into multiple servers, the total number of rows in each table in each database is reduced. This reduces index size, which generally improves search performance. A database shard can be placed on separate hardware, and multiple shards can be placed on multiple machines. This enables a distribution of the database over a large number of machines, allowing database performance to be spread over multiple machines, greatly improving overall performance.Many new non-relational databases (commonly known as NoSQL databases) such as Cassandra, MongoDb and Hbase have been created with database sharding as a key feature. Bring Data closer to user (Caching) – Caching has been adopted and used very well by most of the Consumer Business Apps. Open source products like memcache provide caching options across the tiers (web tier/app tier and data tier). Memcache provides a reliable alternative to the traditional caching solutions – coherence, terracotta. Further, the NoSQL solutions employ the caching engine to speed up the database read and write operations. Couchdb uses the memcache to provide an in memory read/write solution. Service provider/consumer model – Another pattern that has emerged is the Service provider and consumer. It is derivative of the SOA model but leaner and simpler. The business functionality is exposed as a set of services via RESTful API with JSON data format. The presentation layers are the consumers that use these services to build up the user experience. The technologies to build the service and provider can be completely separate. Technologies are chosen based on what is best for the use case. Contracts are enforced by Service version and definition only. Front ends are typically built using PHP or Ruby over rails. Services are built using Scala, Akka, C++, Java etc.Why Enterprises are looking at these patterns?Enterprises have started adopting cloud (public/private) by and large. Elastic scaling means responding to the changing load pattern on real time basis. In the absence of application ability to scale, all that investment into cloud is waste The traditional CPU/Core based licensing models are proving to be costly in the cloud world. Enterprise need to adopt the OSS frameworks/solutions that do not come with licensing baggage The user expectations have gone up by few notches. Enterprise applications are compared and expected to have same resiliency & performance as any other Internet Scale application Scale up model(adding more CPUs) for enterprise applications comes with its own headache of additional capital expenditure. Scale out models(add more smaller servers) that rely on commodity servers or can run over a hybrid cloud are becoming more cost effective solutions Enterprises are going global which requires the systems to be up and available 24X7. Currently tightly coupled application designs do not lend very well to the scalability patternReference: Application Scalability: Still elusive for Enterprises Apps from our JCG partner Munish K Gupta at the Tech Spot blog....
spring-data-logo

Hibernate native SQL features into your Spring Data Repository

JPA provides @NamedNativeQuery for you to use native SQL. However, the usage is not so convenient, especially when you need to map multiple entities in your native SQL. You have to define a set of SqlResultSetMapping mapping which is quite error prone. For those who have used Hibernate native SQL features before, you will find that it is much more easier to use than JPA’s @NamedNativeQuery. In recent projects, I am using Spring Data JPA. I have added hibernate native query features to my Spring Data base repostory. You can now perform native query in JPA without SqlResultSetMapping. 1. Add you cusomt annotation @NativeQueries and @NativeQuery @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface NativeQueries { NativeQuery[] queries() default {}; }@Retention(RetentionPolicy.RUNTIME) public @interface NativeQuery { String name() default ""; String sql() default ""; }2. Add the method “queryNatively” in base Spring Data Repository. If you do not know how to add custom behaviour to your Spring data JPA base repository, please see my previous post for how to customize your Spring data JPA base repository for detail. You can see in previous post that I intentionally expose the repository interface (i.e. the springDataRepositoryInterface property) in the GenericRepositoryImpl. This small tricks enable me to access the annotation in the repository interface easily. public List queryNatively(String nativeQueryName, LinkedHashMap<String,Class<?>> inEntityClasses, Map inParams ){ SQLQuery query = this.createHibernateNativeQuery( nativeQueryName, inParams ); //add entities if (inEntityClasses!=null) { for (Object key: inEntityClasses.keySet()) { String entityClassAlias = key.toString(); Class<?> entityClass = (Class<?>)inEntityClasses.get(key); query.addEntity(entityClassAlias,entityClass); } } //add parameter if (inParams != null){ for (Object key: inParams.keySet()) { String queryParamName = key.toString(); Object queryParamValue = inParams.get(key); query.setParameter(queryParamName, queryParamValue); } } return (query!=null)? query.list() : null ; }private SQLQuery createHibernateNativeQuery (String nativeQueryName, Map inParams ){ if (GenericRepository.class.isAssignableFrom(getSpringDataRepositoryInterface())) { Annotation nativeQueryAnn = getSpringDataRepositoryInterface().getAnnotation(NativeQueries.class); if(nativeQueryAnn != null){ NativeQueries nativeQueries = (NativeQueries)nativeQueryAnn; NativeQuery[] queries = nativeQueries.queries(); for (NativeQuery sqlquery : queries) { if (StringUtils.equals(nativeQueryName, sqlquery.name())) { String sql = sqlquery.sql(); Session hiernateSess = em.unwrap(Session.class); SQLQuery query = hiernateSess.createSQLQuery(sql); //add parameter if (inParams != null){ for (Object key: inParams.keySet()) { String queryParamName = key.toString(); Object queryParamValue = inParams.get(key); query.setParameter(queryParamName, queryParamValue); } } return query; } } } } return null; }3. Example Usage In your repositry interface, define which native SQL queries you want to use through your @NativeQueries and @NativeQuery annotation. The usage is just similar to calling hibernate native query features. You could just see the hibernate alias and property references. @NativeQueries ( queries = { @NativeQuery(name="query1", sql="SELECT {cat.*}, {mother.*} FROM CATS c, CATS m WHERE c.MOTHER_ID = c.ID and c.name = :catName "), @NativeQuery(name="query2", sql="SELECT {cat.*} FROM CATS where c.ID = :catName") } ) public interface CatRepository extends GenericRepository<Cat, Long> { }In your service or business class that inject your repository, you could just simply call the queryNatively() method to perform native SQL query. @Service public class CatService { @Inject private CatRepository catRepository; public List<Cat> searchCat( String catName) { List<Cat> catList; // Add entity mapping for your query HashMap<String, Object> inParams = new HashMap<String, Object>(); inParams.put("catName", "Felix"); // Prepare parameters for your native sql LinkedHashMap<String, Object> entityMap = new LinkedHashMap<String, Object>(); entityMap.put("cat", Cat.class); entityMap.put("mother",Mother.class); catList = catRepository.queryNatively( "query1", "",entityParam); return catList; } }Reference: Adding Hibernate native SQL features into your Spring Data Repository from our JCG partner Boris Lam at the Programming Peacefully blog....
android-logo

Android Voice Recognition Tutorial

You may have heard about the “ Google Now project” where you give the voice command and Android fetches result for you. It recognizes your voice and converts it into the text or takes the appropriate action. Have you ever thought how is it done? If your answer is voice recognition API, then you are absolutly right. Recently while playing with Android voice recognition APIs, I found some interesting stuffs. APIs are really easy to use with application. Given below is a small tutorial on voice/speech recognition API. The final application will look similar to that of application shown below. The application may not work on the Android Emulator because it doesn’t support voice recognition. But the same can work on the phone.Project Information: Meta-data about the project. Platform Version : Android API Level 15. IDE : Eclipse Helios Service Release 2 Emulator : Android 4.1(API 16) Prerequisite: Preliminary knowledge of Android application framework, and Intent. Voice recognition feature can be achieved by RecognizerIntent. Create an Intent of type RecognizerIntent and pass the extra parameters and start activity for the result. It basically starts the recognizer prompt customized by your extra parameters. Internally voice recognition communicates with the server and gets the results. So you must provide the internet access permission for the application. Android Jelly Bean(API level 16) doesn’t require internet connection to perform voice recognition. Once the voice recognition is done, recognizer returns value in onActivityResult() method parameters. First create project by Eclipse > File> New Project>Android Application Project. The following dialog box will appear. Fill the required field, i.e Application Name, Project Name and Package. Now press the next button. Once the dialog box appears, select the BlankActivity and click the next button.Fill the Activity Name and Layout file name in the dialog box shown below and hit the finish button.This process will setup the basic project files. Now we are going to add four buttons in the activity_voice_recognition.xml file. You can modify the layout file using either Graphical Layout editor or xml editor. The content of the file is shown below. As you may notice that we have attached speak() method with button in onClick tag. When the button gets clicked, the speak() method will get executed. We will define speak() in the main activity. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" ><EditText android:id="@+id/etTextHint" android:gravity="top" android:inputType="textMultiLine" android:lines="1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/etSearchHint"/><Button android:id="@+id/btSpeak" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="speak" android:padding="@dimen/padding_medium" android:text="@string/btSpeak" tools:context=".VoiceRecognitionActivity" /><Spinner android:id="@+id/sNoOfMatches" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@array/saNoOfMatches" android:prompt="@string/sNoOfMatches"/><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/tvTextMatches" android:textStyle="bold" /><ListView android:id="@+id/lvTextMatches" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>You may have noticed that the String constants are being accessed from the resource. Now add the string constants in string.xml. This file should look similar to the one shown below. <resources> <string name="app_name">VoiceRecognitionExample</string> <string name="btSpeak">Speak</string> <string name="menu_settings">Settings</string> <string name="title_activity_voice_recognition">Voice Recognition</string> <string name="tvTextMatches">Text Matches</string> <string name="sNoOfMatches">No of Matches</string> <string name="etSearchHint">Speech hint here</string> <string-array name="saNoOfMatches"> <item>1</item> <item>2</item> <item>3</item> <item>4</item> <item>5</item> <item>6</item> <item>7</item> <item>8</item> <item>9</item> <item>10</item> </string-array> </resources>Now let’s define the Activity class. This activity class, with the help of checkVoiceRecognition() method, will first check whether the Voice recognition is available or not. If voice recognition feature is not available, then toast a message and disable the button. Speak() method is defined here which gets called once the speak button is pressed. In this method we are creating RecognizerIntent and passing the extra parameters. The code below has embedded comments which makes it easy to understand. package com.rakesh.voicerecognitionexample;import java.util.ArrayList; import java.util.List;import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.speech.RecognizerIntent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast;public class VoiceRecognitionActivity extends Activity { private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;private EditText metTextHint; private ListView mlvTextMatches; private Spinner msTextMatches; private Button mbtSpeak;@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_voice_recognition); metTextHint = (EditText) findViewById(R.id.etTextHint); mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches); msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches); mbtSpeak = (Button) findViewById(R.id.btSpeak); checkVoiceRecognition() }public void checkVoiceRecognition() { // Check if voice recognition is present PackageManager pm = getPackageManager(); List<resolveinfo> activities = pm.queryIntentActivities(new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() == 0) { mbtSpeak.setEnabled(false); mbtSpeak.setText("Voice recognizer not present") Toast.makeText(this, "Voice recognizer not present", Toast.LENGTH_SHORT).show(); } }public void speak(View view) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);// Specify the calling package to identify your application intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass() .getPackage().getName());// Display an hint to the user about what he should say. intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText() .toString());// Given an hint to the recognizer about what the user is going to say //There are two form of language model available //1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases //2.LANGUAGE_MODEL_FREE_FORM : If not sure about the words or phrases and its domain. intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);// If number of Matches is not selected then return show toast message if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) { Toast.makeText(this, "Please select No. of Matches from spinner", Toast.LENGTH_SHORT).show(); return; }int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem() .toString()); // Specify how many results you want to receive. The results will be // sorted where the first result is the one with higher confidence. intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches); //Start the Voice recognizer activity for the result. startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); }@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)//If Voice recognition is successful then it returns RESULT_OK if(resultCode == RESULT_OK) {ArrayList<string> textMatchList = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);if (!textMatchList.isEmpty()) { // If first Match contains the 'search' word // Then start web search. if (textMatchList.get(0).contains("search")) {String searchQuery = textMatchList.get(0); searchQuery = searchQuery.replace("search",""); Intent search = new Intent(Intent.ACTION_WEB_SEARCH); search.putExtra(SearchManager.QUERY, searchQuery); startActivity(search); } else { // populate the Matches mlvTextMatches .setAdapter(new ArrayAdapter<string>(this, android.R.layout.simple_list_item_1, textMatchList)); }} //Result code for various error. }else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){ showToastMessage("Audio Error"); }else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){ showToastMessage("Client Error"); }else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){ showToastMessage("Network Error"); }else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){ showToastMessage("No Match"); }else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){ showToastMessage("Server Error"); } super.onActivityResult(requestCode, resultCode, data); } /** * Helper method to show the toast message **/ void showToastMessage(String message){ Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }Here is the Android manifest file. You can see that INTERNET permission has been provided to the application because of the voice recognizer’s need to send the query to the server and get the result. <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.rakesh.voicerecognitionexample" android:versionCode="1" android:versionName="1.0" ><uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <!-- Permissions --> <uses-permission android:name="android.permission.INTERNET" /><application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" ><activity android:name=".VoiceRecognitionActivity" android:label="@string/title_activity_voice_recognition" > <intent-filter> <action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>Once you are done with coding then connect the phone with your system and hit the run button on Eclipse IDE. Eclipse will install and launch the application. You will see the following activities on your device screen. In the next tutorial, we will learn how to use the new voice recognition API introduced in Android Jelly Bean(API level 16) along with the examples. If you are interested in the source code, then you can get it from github. Reference: Tutorial on Android Voice recognition from our JCG partner Rakesh Cusat at the Code4Reference blog....
ignite-realtime-openfire-logo

Android: File transfer with asmack and Openfire

I have seen many peoples struggling from file transfer in asmack – Android build environment and patches for smack. I tried same library with Openfire server after some debugging got success in it. So I will like to share my problem and solution for it. I found that the problem is in Byte Stream host, it tries to connect to wrong host for initiating file transfer using byte streams. If you have not configured the file transfer proxy properly then it will choose 127.0.0.1 or localhost or any internally configured host/ip as a bytestream host, which in android is not considered as proper ip for communicating. But wait then why it is working properly with desktop client with same server. The reason is desktop clients can easily identify this ips and can use it to open socket for file transfer. The variable names used in following discussions are:Name MeaningmyHost The hostname of machine on which Openfire is running.user1@myHost File transfer initiator useruser2@myHost Recipient of fileHow to know which host is chosen for byte streams: (Following XMLs are shown as they are sent and received to the file transfer initiator.)First query other client for information about supported features:Sent: <iq id='x1ixz-13' to='user2@myHost/Smack' type='get'> <query xmlns='http://jabber.org/protocol/disco#info'></query> </iq> Received: <iq id='x1ixz-13' to='user1@myHost/Smack' type='result' from='user2@myHost/Smack'> <query xmlns='http://jabber.org/protocol/disco#info'> <!—some other items --> <feature var='http://jabber.org/protocol/bytestreams'/> <!—some other items --> </query> </iq> Here you can know that whether bytestream file transfer is supported on the client other side or not. If you see a xml like above in response then it’s supported on the other side and you can go further.Query server for disco items:Sent: <iq id='x1ixz-14' to='myHost' type='get'> <query xmlns='http://jabber.org/protocol/disco#items'></query> </iq> Received: <iq type='result' id='x1ixz-14' from='myHost' to='user1@ myHost /Smack'> <query xmlns='http://jabber.org/protocol/disco#items'> <!—some other items --> <item jid='proxy. myHost ' name='Socks 5 Bytestreams Proxy'/> <!—some other items --> </query> </iq> Here you will receive various items for different items supported by server like , file transfer proxy, search service, conference service… The item we should look for is ` Socks 5 Bytestreams Proxy `.Request for more information on proxySent: <iq id='x1ixz-19' to='proxy. myHost ' type='get'> <query xmlns='http://jabber.org/protocol/bytestreams'/> </iq> Received: <iq type='result' id='x1ixz-19' from='proxy. myHost ' to='user1@ myHost /Smack'> <query xmlns='http://jabber.org/protocol/bytestreams'> <streamhost jid='proxy. myHost ' host=' myHost ' port='7777'/> </query> </iq> Here the host in the <streamhost> is the key for the file transfer. You have to make sure that this host is accessible from your android phone. It should not be like localhost, 127.0.0.1 or any company’s internal configured server which is not accessible outside of the company. It must be a publicly accessible ip address or host. To configure proper proxy add/change these 3 properties in Openfire:xmpp.proxy.enabled – true xmpp.proxy.port – 7777 xmpp.proxy.externalip – [publicly accessible host or ip]The code for file transfer: FileTransferManager manager = new FileTransferManager(connection); OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer('usre2@myHost/Smack'); File file = new File(filenameWithPath); try { transfer.sendFile(file, 'test_file'); } catch (XMPPException e) { e.printStackTrace(); } while(!transfer.isDone()) { if(transfer.getStatus().equals(Status.error)) { System.out.println('ERROR!!! ' + transfer.getError()); } else if (transfer.getStatus().equals(Status.cancelled) || transfer.getStatus().equals(Status.refused)) { System.out.println('Cancelled!!! ' + transfer.getError()); } try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error) || transfer.getStatus().equals(Status.cancelled)){ System.out.println('refused cancelled error ' + transfer.getError()); } else { System.out.println('Success'); } And the code for file receive: FileTransferManager manager = new FileTransferManager(connection); manager.addFileTransferListener(new FileTransferListener() { public void fileTransferRequest(final FileTransferRequest request) { new Thread(){ @Override public void run() { IncomingFileTransfer transfer = request.accept(); File mf = Environment.getExternalStorageDirectory(); File file = new File(mf.getAbsoluteFile()+'/DCIM/Camera/' + transfer.getFileName()); try{ transfer.recieveFile(file); while(!transfer.isDone()) { try{ Thread.sleep(1000L); }catch (Exception e) { Log.e('', e.getMessage()); } if(transfer.getStatus().equals(Status.error)) { Log.e('ERROR!!! ', transfer.getError() + ''); } if(transfer.getException() != null) { transfer.getException().printStackTrace(); } } }catch (Exception e) { Log.e('', e.getMessage()); } }; }.start(); } }); Also configure ProviderManager to properly decode/parse bytestreams and other required xmls: ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/bytestreams', new BytestreamsProvider()); ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#items', new DiscoverItemsProvider()); ProviderManager.getInstance().addIQProvider('query','http://jabber.org/protocol/disco#info', new DiscoverInfoProvider()); The asmack library I used was asmack-jse-buddycloud.jar. Reference: File transfer in android with asmack and Openfire from our JCG partner Harsh Raval at the harryjoy blog....
jboss-hibernate-logo

Hibernate lazy/eager loading example

This post will focus on why and how we use the concepts known as LAZY and EAGER loading in an application and how to use Spring’s hibernate template to load our LAZY entities in an EAGER fashion. And of course as the title itself suggests, we will show this by an example. The scenario is as such; You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time. So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys. But you are faced with another issue. When the time comes for a family trip, you want him to bring along his toys because the kid will be bored with the trip otherwise. But since you strictly enforced LAZY on the child’s toy, you are unable to ask him to bring along the toys. This is where EAGER fetching comes into play. Let us first see our domain classes. package com.fetchsample.example.domain;import java.util.HashSet; import java.util.Set;import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table;/** * Holds information about the child * * @author dinuka.arseculeratne * */ @Entity @Table(name = 'CHILD') @NamedQuery(name = 'findChildByName', query = 'select DISTINCT(chd) from Child chd left join fetch chd.toyList where chd.childName=:chdName') public class Child {public static interface Constants { public static final String FIND_CHILD_BY_NAME_QUERY = 'findChildByName';public static final String CHILD_NAME_PARAM = 'chdName'; }@Id @GeneratedValue(strategy = GenerationType.AUTO) /** * The primary key of the CHILD table */ private Long childId;@Column(name = 'CHILD_NAME') /** * The name of the child */ private String childName;@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) /** * The toys the child has. We do not want the child to have the same toy more than * once, so we have used a set here. */ private Set<Toy> toyList = new HashSet<Toy>();public Long getChildId() { return childId; }public void setChildId(Long childId) { this.childId = childId; }public String getChildName() { return childName; }public void setChildName(String childName) { this.childName = childName; }public Set<Toy> getToyList() { return toyList; }public void addToy(Toy toy) { toyList.add(toy); }}package com.fetchsample.example.domain;import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;/** * Hols data related to the toys a child possess * * @author dinuka.arseculeratne * */ @Entity @Table(name = 'TOYS') public class Toy {@Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = 'TOY_ID') /** * The primary key of the TOYS table */ private Long toyId;@Column(name = 'TOY_NAME') /** * The name of the toy */ private String toyName;public Long getToyId() { return toyId; }public void setToyId(Long toyId) { this.toyId = toyId; }public String getToyName() { return toyName; }public void setToyName(String toyName) { this.toyName = toyName; }@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((toyName == null) ? 0 : toyName.hashCode()); return result; }@Override /** * Overriden because within the child class we use a Set to * hold all unique toys */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Toy other = (Toy) obj; if (toyName == null) { if (other.toyName != null) return false; } else if (!toyName.equals(other.toyName)) return false; return true; }@Override public String toString() { return 'Toy [toyId=' + toyId + ', toyName=' + toyName + ']'; }}So as you can see, we have two simple entities representing the child and toy. The child has a one-to-many relationship with the toys which means one child can have many toys (oh how i miss my childhood days). Afterwards we need to interact with the data, so let us go ahead and define out DAO(Data access object) interface and implementation. package com.fetchsample.example.dao;import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional;import com.fetchsample.example.domain.Child;/** * The basic contract for dealing with the {@link Child} entity * * @author dinuka.arseculeratne * */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public interface ChildDAO {/** * This method will create a new instance of a child in the child table * * @param child * the entity to be persisted */ public void persistChild(Child child);/** * Retrieves a child without his/her toys * * @param childId * the primary key of the child table * @return the child with the ID passed in if found */ public Child getChildByIdWithoutToys(Long childId);/** * Retrieves the child with his/her toys * * @param childId * the primary key of the child table * @return the child with the ID passed in if found */ public Child getChildByIdWithToys(Long childId);/** * Retrieves the child by the name and with his/her toys * * @param childName * the name of the child * @return the child entity that matches the name passed in */ public Child getChildByNameWithToys(String childName);}package com.fetchsample.example.dao.hibernate;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import com.fetchsample.example.dao.ChildDAO; import com.fetchsample.example.domain.Child;/** * The hibernate implementation of our {@link ChildDAO} interface * * @author dinuka.arseculeratne * */ public class ChildDAOHibernateImpl extends HibernateDaoSupport implements ChildDAO {/** * {@inheritDoc} */ public void persistChild(Child child) { getHibernateTemplate().persist(child); }/** * {@inheritDoc} */ public Child getChildByIdWithoutToys(Long childId) { return getHibernateTemplate().get(Child.class, childId); }/** * {@inheritDoc} */ public Child getChildByIdWithToys(Long childId) { Child child = getChildByIdWithoutToys(childId); /** * Since by default the toys are not loaded, we call the hibernate * template's initialize method to populate the toys list of that * respective child. */ getHibernateTemplate().initialize(child.getToyList()); return child; }/** * {@inheritDoc} */ public Child getChildByNameWithToys(String childName) { return (Child) getHibernateTemplate().findByNamedQueryAndNamedParam( Child.Constants.FIND_CHILD_BY_NAME_QUERY, Child.Constants.CHILD_NAME_PARAM, childName).get(0);}}A simple contract. I have four main methods. The first one of course just persists a child entity to the database. The second method retrieves the Child by the primary key passed in, but does not fetch the toys. The third method first fetches the Child and then retrieves the Child’s toys using the Hibernate template’s initialize() method. Note that when you call the initialize() method, hibernate will fetch you LAZY defined collection to the Child proxy you retrieved. The final method also retrieves the Child’s toys, but this time using a named query. If we go back to the Child entity’s Named query, you can see that we have used ‘left join fetch‘. It is the keyword fetch that actually will initialize the toys collection as well when returning the Child entity that qualifies. Finally i have my main class to test our functionality; package com.fetchsample.example;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.fetchsample.example.dao.ChildDAO; import com.fetchsample.example.domain.Child; import com.fetchsample.example.domain.Toy;/** * A test class * * @author dinuka.arseculeratne * */ public class ChildTest {public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( 'com/fetchsample/example/spring-context.xml');/** * First we initialize a child */ Child child = new Child();/** * A cool ben 10 action figure */ Toy ben10 = new Toy(); ben10.setToyName('Ben 10 figure');/** * A even more cooler spider man action figure */ Toy spiderMan = new Toy(); spiderMan.setToyName('Spider man figure');child.setChildName('John'); /** * Add the toys to the collection */ child.addToy(ben10); child.addToy(spiderMan);ChildDAO childDAO = (ChildDAO) context.getBean('childDAO');childDAO.persistChild(child);Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L); // The following line will throw a lazy initialization error since we have // defined fetch type as LAZY in the Child domain class. // System.out.println(childWithToys.getToyList().size());Child childWithToys = childDAO.getChildByIdWithToys(1L); System.out.println(childWithToys.getToyList().size());Child childByNameWithToys = childDAO.getChildByNameWithToys('John');System.out.println(childByNameWithToys.getToyList().size());} }Defining your base Entity as LAZY is a good practice since in many occasions, you might not want the collections within an entity, but just want to interact with the data in your base entity. But in the event of you needing the data of your collections, then you can use either of the methods mentioned before. That is about it for today. For anyone who wants to try out the example, i have uploaded it here. Reference: Lazy/Eager loading using hibernate by example from our JCG partner Dinuka Arseculeratne at the My Journey Through IT blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
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