X

Recent Posts

Cloud

Moving Renewable Energy Embedded Systems Into the Cloud: Activate Containment Field

NOTE: This is the third installment in my ongoing development of a fully cloud-connected, IoT-based Renewable Energy system. Please visit these earlier articles if you'd like to review what was discussed previously: Episode 1: In the Beginning... Episode 2: The Devil is in the Details, er, Devices For the past few days, I've been focusing upon creating Docker containers that provide the foundations for a hosted application and its underlying database. What's that? Why Docker? I'm glad you asked! Containers as Far as the Eye Can See Many people hail containers in general - and Docker in particular - as being the "next big thing" in application deployment. There are good arguments for and against, and I'm not going to repeat those arguments here...but I will point out some things that make using Docker appealing for me personally: Docker is great for development While there are indisputable challenges for production environments (security, maturity, limited tooling, etc.), Docker generally makes setting up environments fast and fairly easy. Repeatability/Infrastructure as Code (DevOps) It's not only fast and easy to perform the initial environment setup; re-creating environments (or duplicating them) becomes almost trivial. Sure, it takes a bit of time to work through creating a Dockerfile (more on this later), but going from that to running machine is mind-bogglingly fast. Even the first time. :) Oracle embraces containers This point will mean nothing to some and everything to others, but it's another data point: Oracle has offered WebLogic, MySQL, and Oracle Linux Docker images for some time already and recently has announced coming support for containers in several product offerings (Cloud/Linux/Solaris). And (too) many more reasons I won't go into the minute details here, but please check back here or in my Twitter feed for future Docker discussions, good and bad. :) Fabricating Containers Three Docker concepts that are key to this discussion are those of Dockerfile, image, and container. The concepts are fairly straightforward once you understand how they relate to each other. A Dockerfile is essentially a file containing directives you provide for Docker to use to create an image. In a Dockerfile, you can specify another image to use as the basis for this one, commands to run, and ports to expose, among other things. A Dockerfile is only necessary if you plan to modify an existing image in some way. An image is an assembly of Operating System and application layers that can be used as a template for creating a running machine, i.e. container. Images contain the Operating System and any applications and configuration performed in preparation for running. This allows many containers to be created quickly and identically. A container is one running instance of a particular image. You can run multiple instances of, for example, a MySQL database image, and each is a separate container. But back to our system! Part of the targeted Cloud Architecture must support the collection and storage of data: ongoing status of the Renewable Energy (RE) system and sensors, actual readings, etc. To accommodate this, I started with: The official MySQL image to provide the backend database, and The "WebLogic on Docker" image build These provide a great jumping-off point. Here is an overview of the steps I took to prepare them for what's in store. MySQL The official MySQL image has most of what we need from a database container, but we need to specify a few additional parameters to lay the groundwork for our application; among other things, we must create a database! This is accomplished by executing the following command (explanation of parameters to follow): docker run --name mymysql -d -e MYSQL_ROOT_PASSWORD=<password> -e MYSQL_DATABASE=<db_to_create> -e MYSQL_USER=<username> -e MYSQL_PASSWORD=<password> mysql:5.7.8 docker run : Runs a docker container --name mymysql : Assigns the name 'mymysql' to the container (running instance) -d : Runs the container as a daemon, in the background (non-interactive mode) -e MYSQL_ROOT_PASSWORD=<password> : Assigns the specified password to MySQL's root user -e MYSQL_DATABASE=<db_to_create> : Creates a database with the specified name -e MYSQL_USER=<username> : Creates a non-privileged database user (e.g. application user) -e MYSQL_PASSWORD=<password> : Password for MYSQL_USER specified above mysql:5.7.8 : Image name:tag (version) upon which to base this container We will create the necessary tables from our application, but creating the underlying database and the application's database user while initializing the container simplifies things greatly. WebLogic The WebLogic setup was a bit more complicated than for MySQL, although part of that was due to changes I made to the original configuration in GitHub, updating the various files to point to WebLogic Server 12.1.3 update 3 and JDK 8 update 51 (pull request merged, thanks Bruno!). Here are the key steps I followed (excluding those necessary to make changes to the above files, which won't be repeated): "git clone" the oracle/docker repository from GitHub Download the current JDK and WebLogic .zip distribution, placing them in the OracleWebLogic/dockerfiles/12.1.3 directory within the cloned repo, to be used by the build script From the OracleWebLogic/dockerfiles directory, run ./buildDockerImage.sh -d to create a basic WebLogic Server (WLS) image Edit OracleWebLogic/samples/12c-domain/container_scripts/create-wls-domain.py, uncommenting and providing appropriate values in the section to create a JDBC connection (in our case, for our MySQL database/schema) From the OracleWebLogic/samples/12c-domain/ directory, run docker build -t weblogicdomain . to create a new image derived from the basic WLS image above, this time with a created domain and some resources (JMS, JDBC) Finally, execute the following command to create and run a WebLogic container and link it to the MySQL container we've started: docker run --name wlsdomain --link mymysql:mymysql -d -p 8001:8001  weblogicdomain:latest startWebLogic.sh docker run : Runs a docker container --name wlsdomain : Assigns the name 'wlsdomain' to the container (running instance) --link mymysql:mymysql : Links this container to the container named 'mymysql', identifying it within this container as 'mymysql' -d : Runs the container as a daemon, in the background (non-interactive mode) -p 8001:8001 : Publishes port 8001 from the container to port 8001 on the host weblogicdomain:latest : Image name:tag (version) upon which to base this container startWebLogic.sh : Run this shell script when container starts Status Update Both containers are running smoothly and thus far, all appears to be working properly. The true test will be when I drop real code in there, create tables and (of course), let the application do its thing. Spoiler alert: that's coming up next. :) Next Week's Episode Thanks for reading! Tune in next week as we do a significant refactor/rewrite of the local enterprise Java application and deploy it (well, version 0.1) to its new home. Should be fun! Onward and upward, Mark Just a reminder: I'll be presenting this and more in a JavaOne 2015 session entitled "Moving Renewable Energy Embedded Systems Into the Cloud", session CON10262, along with lessons learned and some other nuggets I pick up along the way. If you're there, come by and say "Hi!"

NOTE: This is the third installment in my ongoing development of a fully cloud-connected, IoT-based Renewable Energy system. Please visit these earlier articles if you'd like to review what was...

Cloud

Moving Renewable Energy Embedded Systems Into the Cloud: The Devil is in the Details, er, Devices

NOTE: This is the second installment in my ongoing (re-)development of a fully cloud-connected, IoT-based Renewable Energy system. Please click here to read the initial article for more information about the overall vision, "legacy" system, and proposed architecture. Please keep in mind that these things may change to accommodate new requirements, constraints, etc. Agile development depends upon agility.  :) Over the past week, most of my efforts on the system have focused primarily upon expanding the device/sensor capabilities in the IoT node in our utility shed (affectionately referred to as the powerhouse), so it's been a very hands-on week. While software architecture and development are my life - very happily so - I really enjoy building interfaces between the virtual and real worlds. There is something intensely gratifying to soldering and assembling components, installing and connecting actuators, and seeing it all *work*. Let's face it, sometimes you just have to interact with the physical world. ;) Hardware in the Powerhouse Node As depicted in the first post's Cloud Architecture diagram, there are a lot of things that could be going on in the shed/powerhouse any any point in time. To better understand this, let's take a deeper look at the hardware present. Providing power to the IoT node are three photovoltaic (PV) panels and a small wind turbine. The solar panels are routed through a charge controller to ensure power feeds only one way (into the batteries); a blocking diode provides similar protection for the wind turbine, guarding against battery discharge. An array of 12V deep cycle batteries acts as storage for energy generated by the aforementioned power sources; devices are connected to a wiring block from the batteries, which are wired in parallel to increase system storage capacity while maintaining voltage. Sensors previously (and still) active in the system include temperature & humidity (environmental) and amperage & voltage (power). Amps/volts readings were monitored by wiring the Arduino serially into the sensor (feeding the Arduino itself) due to the requirement there be a load on the circuit to monitor. FUN FACT: Without some kind of load in the circuit, it's a short...and you can (very literally) smoke a power sensor that way. Trust me. Or if you don't, order a spare. ;) Outputs for the "legacy" system include an LED light that indicated "system normal" condition and one of the two following power outputs, depending upon season: A fan, used to circulate air over the devices during warmer months of the year A heater, used to maintain a reasonable temperature within the powerhouse during colder months The system has two modes - Automatic and Manual (override) - which will be re-implemented in the new system as well. In automatic mode currently, when temperatures within the powerhouse are fairly moderate (I chose a range of 1-31 degrees Celsius/34-88 degrees Fahrenheit, exclusive), the status light is enabled and the fan/heater (whichever applies at that time of year) is turned off. When temps break out of the defined moderate range, the status light is extinguished and power is fed to the appropriate output to provide cool air or heat to the components. When the temperature again falls within the acceptable range, the actions are reversed: status light on, fan/heater off. When the system is placed into Manual mode, any combination of settings can be selected. Over the past 7-10 days, I've installed two automotive (2-wire) linear actuators on the windows in opposite sides of the shed and connected them to an 8-channel relay, putting to use four of the eight channels to open and close the windows as desired. I've also incorporated a weather subsystem that includes the following measurement/feedback capabilities: Wind direction Windspeed Rainfall Barometric pressure Relative humidity (original legacy system source also remains for time being) Temperature (two additional sources in addition to original system source) Luminosity (ambient light level) Reading status light (provides visual feedback when each new reading is taken) Status Update After some system re-configuration and device installation, all output devices (currently lights, fans, and actuators) are working flawlessly. All sensors are providing data, but readings from the new humidity sensor (humidity and temperature) are returning errant values. Since the other new weather components integrated with the humidity sensor are providing verifiably accurate data, there's a good chance it's due to a faulty sub-component; I've contacted the vendor for assistance and will provide an update here once we isolate and resolve the issue. Having a Raspberry Pi as the IoT node concentrator/gateway provides more than just a very able platform for nearly anything that may be required for processing and communication of sensor data; it also allows us to "maintain a visual" of the powerhouse's power center. Onboard the Pi is a camera that provides a near real-time video feed so we can see firsthand what is happening as the system responds automatically to readings or to commands we send it when in Manual (override) mode. A Sneak Peek Below are some photos of the power panel and "brains" of the powerhouse IoT node, along with a couple shots of the actuators that open and close the windows. Just a hint of things to come. :) Thanks for reading! Tune in next week as we take the first steps toward configuring a containerized cloud environment to serve as the foundation for the JCS/application server portion of the cloud architecture(s). Here comes the GOOD STUFF. B) Onward and upward! Mark Just a reminder: I'll be presenting this and more in a JavaOne 2015 session titled "Moving Renewable Energy Embedded Systems Into the Cloud", session CON10262, along with lessons learned and some other nuggets I pick up along the way. If you're there, come by and say "Hi!"

NOTE: This is the second installment in my ongoing (re-)development of a fully cloud-connected, IoT-based Renewable Energy system. Please click here to read the initial article for more information...

Cloud

Moving Renewable Energy Embedded Systems Into the Cloud: In the Beginning...

"It was a dark and stormy night." No, not that kind of beginning. Although (spoiler alert), there are clouds involved.  :) I've been running a Renewable Energy (RE) system at my house for the past three years. It's comparatively small, providing power only to our 12'x16', two-story utility shed in a corner of our backyard. Although there are electrical connections running between house and shed, the RE system provides nearly all power consumed outside of our house...and intentionally so. I wanted to get a better understanding of renewable energy systems as a whole, and I also wanted to be able to monitor everything (at all times!) and perhaps even make adjustments to system settings from the comfort of our home. No single system accomplished all I had in mind...so I wrote one. Initially, Dr. Jose Pereda and I teamed up to write parallel systems - one in the US, one in Spain - and we used Java SE Embedded and Java EE (running on Raspberry Pis, no less!) to provide the backbone(s) of the systems. This was a fun and instructive exercise, as it encouraged us to work efficiently and leverage all we could within each platform without adding unnecessary baggage. And the system has proven its robustness, having run for over three years with impressive uptime and (lack of) maintenance. But systems evolve, and the ubiquity, reliability, and compelling (low!) price of the cloud opens a great deal of possibilities for this system that I've been eager to explore. Here is the existing architecture for my RE system: Click here for full-size diagram of Existing Architecture And here is the target architecture I'll be implementing over the next few weeks: Click here for full-size diagram of Cloud Architecture As you can see, I'm refactoring and expanding a bit. And while I'm doing so, I'll be writing about it here. Once everything is finished, I'll be presenting this and more in a JavaOne 2015 session titled "Moving Renewable Energy Embedded Systems Into the Cloud", session CON10262, along with lessons learned and some other nuggets I pick up along the way. I'm agilely following agile principles (get it?), and DevOps principles and tools have a role to play here as well. So I'll be building as needed, deploying continuously (hardware and software), and reviewing and revising frequently. Think of it as a cloud- and IoT-centered microproject. :) Looking forward to sharing it all with you here over the next few weeks. Onward and upward!Mark

"It was a dark and stormy night." No, not that kind of beginning. Although (spoiler alert), there are clouds involved.  :) I've been running a Renewable Energy (RE) system at my house for the past...

IoT-Embedded

How to Create a Positronic Brain for Your Drone

For this year’s JavaOne, Jim Weaver, Sean Phillips, and I presented a session entitled Creating Our Robot Overlords: Autonomous Drone Development with Java and the Internet of Things. We invested a lot of energy and had a great time developing several components that contributed to a more intelligent drone, and the presentation was well-received. There is SO much to be done, though, and we’re just getting started!That said, we’ve been slower than we’d like in sharing some of the materials we created along the way, and we’re trying to catch up with some of those housekeeping chores now. This post is intended to provide a starting point and frame of reference for some of our decisions so far, provide some hints to intentions moving forward, and perhaps explain what may or may not make sense at first blush. Think of it as a map legend. :)We decided early on that there were really two levels of autonomy we could work toward accomplishing, what we referred to very loosely as General Autonomy (GA) and Advanced Autonomy (AA). With the compressed timeline we had for JavaOne, we focussed primarily upon providing a reliable level of General Autonomy. Here is how we differentiated:General Autonomy (GA): The drone is controlled by its onboard (Raspberry Pi) brain, with instructions issued by the brain via a Java (SE Embedded) program. The brain directs the drone’s movements step by step, e.g. instructing it to move a specified distance/speed/duration in a particular direction. An entire flight sequence is compiled in this manner by the developer, but the Pi executes it entirely from and on the drone itself, with or without external connectivity.Advanced Autonomy (AA): The drone is controlled by its onboard (Raspberry Pi) brain, but rather than a very specific set of task-based instructions, the brain controls the drone using a goal-oriented - and self-adjusting - program. This requires a much greater awareness by the drone of its environment and the ability to extrapolate an initial framework of behavior based upon instructions further from a list of steps and closer to “navigate around the perimeter of this room at an altitude of approximately 2m/6.5’".While a great deal of code was (and is) being developed along both paths, we checked into a repository our JavaOne demo code for sharing; more will certainly follow over time.Just recently, I created a wiki page detailing the steps we used to configure a Raspberry Pi as a "Positronic brain” for our drones (one for each, of course - what kind of mad science do you think we do, anyway?!?!). If you’d like to start working on your own intelligent drone, you can read what we did here and see what you think. This was our "version 1.0" and will change and adapt as platform(s) evolve, but our plan is to keep it up-to-date as we go along.More updates to follow! This is an exciting area to explore, and as I said earlier, we’re just getting started. Join in the fun! How do you ever hope to stay ahead of SkyNet if you don’t help create it?  ;)Cheers,///ark

For this year’s JavaOne, Jim Weaver, Sean Phillips, and I presented a session entitled Creating Our Robot Overlords: Autonomous Drone Development with Java and the Internet of Things. We invested a...

JavaDev

Join Us at JavaOne 2014!

There are some absolutely SUPERB conferences dedicated to Java (the language, the platform, the ecosystem) around the world, and I’ve been privileged to speak at some of them. No two are alike, and that is a good thing! JavaOne San Francisco holds a very special place in that lineup, bringing together a phenomenal mixture of vision, direction, community leadership, and grassroots innovation that is nearly impossible to describe. You just have to be there!This year I’m pleased and honored to be presenting in three sessions, sharing the stage with some of my favorite people from around the world: Jim Weaver, Sean Phillips, David Heffelfinger, Geertjan Wielenga, Jens Deters, José Pereda, and James Gosling. As I said, it’s a genuine honor!Here are the sessions in which I’ll be taking part:Creating Our Robot Overlords: Autonomous Drone Development with Java and the Internet of Things [CON1863]Tuesday, Sep 30, 2:30 PM - 3:30 PM - Hilton - Continental Ballroom 4Who wants a mindless drone? Teach it to “think,” and it can do so much more. But how do you take it from Toy Story to Terminator? This session’s speakers discuss their new open source library, Autonomous4j, for autonomous drone development. Combining this library and some components from their mad science toolkit, they demonstrate how to get your Internet of Things off the ground and do some real cloud computing. In the session, you’ll learn how to write an autonomous drone program with Java 8; deploy it to the drone’s “positronic brain,” an onboard Raspberry Pi; have the Pi guide an AR.Drone to accomplish a task; monitor it via a JavaFX console; and create your own robot overlord. Demos are included: you’ve been warned! With Jim Weaver & Sean Phillips Debugging and Profiling Robots with James Gosling [CON6699]Wednesday, Oct 1, 1:00 PM - 2:00 PM - Hilton - Continental Ballroom 4 James Gosling recently stated that “being able to debug and profile robots out at sea is a truly life-altering experience.” He uses a set of tools—consisting of editors, debuggers, and profilers—that are part of the NetBeans IDE. In this session, Gosling and other speakers introduce you to these tools and show you how easily and quickly you can program and interact with devices via Java tools. Come see how well integrated embedded devices are with the Java ecosystem. With Geertjan Wielenga, Jens Deters, José Pereda, & James Gosling Java Platform, Enterprise Edition Lab 101: An Introduction [HOL1827]Wednesday, Oct 1, 10:00 AM - 12:00 PM - Hilton - Franciscan A/BFor anyone familiar with the Java language but without direct Java Platform, Enterprise Edition (Java EE) experience, the capabilities and APIs in Java EE can seem daunting. Documentation is helpful, and well-written books can make it easier to come up to speed, but isn’t the best way to learn something to actually do it? This session’s speakers hope to smooth the path for anyone curious about Java EE by offering a gentle, yet useful, introduction to four key concepts:• JavaServer Faces (JSF)• Contexts and Dependency Injection (CDI)• Java Persistence API (JPA)• Enterprise JavaBeans (EJB)Using NetBeans and the bundled GlassFish application server, the speakers present each new concept with live code and then help attendees complete hands-on exercises.With David Heffelfinger (and gracious assistance from Sven Reimers, Josh Juneau, Bob Larsen, & Bruno Borges) I’ve said it before: There’s no better place to see what’s happening in the world of Java than JavaOne. Hope to see you there!All the best,Mark

There are some absolutely SUPERB conferences dedicated to Java (the language, the platform, the ecosystem) around the world, and I’ve been privileged to speak at some of them. No two are alike, and...

JavaDev

Don't Create Brittle Software

Every developer is a software user/consumer at various levels, and I'm sure that every one of us has run into a dev tool, library, or component that left us cringing. Why is it so difficult to bend to our will? Why does it seem so broken? WHY DID IT STOP WORKING WITH THE LAST UPDATE??? User-facing software shouldn't break or perform in ways that are "ugly", and if your software is a library/component, neither should your API. Whoever your user is, updates shouldn't break things, and failures (of whatever kind) should be handled gracefully. For example... If your software doesn't facilitate the user's activity, i.e. make it easier, it is at best sub-optimal and may even be unusable. If your library's API doesn't deprecate and migrate changes clearly and gradually, other developers may find it difficult or impossible to use as well. User Experience (UX) is about so much more than a User Interface (UI). Whatever you develop should be clean, as intuitive as possible to use, and work in expected ways. Highly self-configurable (to the extent possible) is a huge plus as well. If you are developing a library or custom control, its value can be measured by two things: The ease with which it can be applied to and cover "default" applications (simplicity) The mechanisms you provide to cover edge cases or "the other 20%" (versatility/extensibility) These two guidelines apply whether you publish your code as open source or not; after all, the goal of open source software is not to taunt other developers with what could have been and force them to do it themselves. Keeping these things in mind can help a developer craft better software that is more useful to more people. Just something that has been on my mind for awhile now... Cheers,Mark Have a horror story you'd like to share? Please don't post names - no need for public floggings (!) - but if you have a particularly bad example that you use as a reminder to write better code, please share it in the comments so we can shudder with you. Misery loves company. :)

Every developer is a software user/consumer at various levels, and I'm sure that every one of us has run into a dev tool, library, or component that left us cringing. Why is it so difficult to bend to...

JavaDev

MonologFX Update: Timed JavaFX Dialogs

When I wrote the original MonologFX dialogs for JavaFX, I was just trying to clean up a few things I'd done in my earlier project, DialogFX, that I felt could have been done better. Based upon some excellent feedback and suggestions, I rolled out the update...just as the OpenJFX team was releasing their own dialog code that is destined to be in JavaFX/OpenJFX. :-) As I mentioned in this previous post, rather than just hoard the code, I released it anyway in the hopes others might continue to find it useful - and updated the dialogs in the JFXtras Labs library as well - but didn't really expect there to be much continued interest. I'm happy to say I was wrong. One of my goals was to make a very simple set of dialogs that worked well in most cases and that just "got out of the developer's way"...tools you didn't have to think about extensively to use in your JavaFX application, just "drop & go". They were never meant to be all things to all people, rather a solid option for most use cases. But... I've gotten some excellent follow-on requests, and I've explored several of them. While I may never have the time to implement them all - and some wander FAR from the original goals - some just fit. One of those ideas was for timed dialogs. What is a Timed Dialog, and When Would I Use It? A few developers pointed out that there are occasions when an app is running unattended and dialogs can either a) stop everything or b) pile up by the droves on the user's desktop. And JFXtras implementer Scott mentioned how nice it would be to have an informational dialog that worked similar to a mail notification, popping up and then disappearing after some pre-determined amount of time. The user should also be able to clear the dialog immediately, of course. Enter the timed dialog. Drawing inspiration from the aforementioned mail notifications and a sample game by colleague Angela Caicedo, I expanded upon Angela's game-switching example to create a (hopefully pleasing) dialog fade in/out effect. Using the number of seconds specified by the developer (you!) via the method setDisplayTime(int displayTime), MonologFX apportions a reasonable percentage of that time to fade in, display, and fade out operations...making user input entirely optional. What Does it Look Like? It's much easier to demo than it is to explain, so I created a quick video of a normal dialog, then a timed one, in action. Click here to watch it on YouTube. Limitations, Caveats, "Keep Off the Grass" Signs A timed dialog is really best suited for informational dialogs - those where there is no user input required, like the aforementioned mail notifications. If a response is required from a user and a dialog disappears of its own volition, which option should be chosen? The "cancel" option would seem best in some cases, and the "default" in others. Creating the fade in/out effect required a non-blocking implementation, which meant that it would always return a value immediately...and in the current design, that is "cancel". Which again points to using them as informational dialogs, but not for obtaining user feedback. So for the foreseeable future, timed dialogs are really focused upon and should be confined to use as informational dialogs. If you need the application user to make a conscious choice prior to proceeding, keep that dialog prominently displayed until you get a response! Where Can I Get Them? I've already pushed the code to my Github repository for MonologFX and the JFXtras-Labs 2.2 and JFXtras-Labs 8.0 repos. And if you just want to download a .jar file and kick the tires, I've put a copy in the MonologFX repo's dist folder. Just download the .zip file, unzip it, and run java -jar MonologFX.jar for a quick demo. Odds & Ends I also made a few architectural changes to MonologFX this weekend during our first-ever "Thanks For Sharing Informal, International HackFest", and more will be integrated over time. Please stay tuned for more information. :-) Happy Coding!Mark

When I wrote the original MonologFX dialogs for JavaFX, I was just trying to clean up a few things I'd done in my earlier project, DialogFX, that I felt could have been done better. Based upon some...

JavaDev

Join me at JavaOne 2013

I'm excited to be able to speak at JavaOne again this year! Last year was an incredible experience, great brain food for anyone committed to Java and the Java ecosystem. This year promises to be even better. This year, I have the privilege of sharing the podium with some of my favorite folks in the world, from around the world! Here are the sessions I'll be taking part in: Session ID: BOF2605Session Title: JavaFX, Widgets, and Apps, Oh My! Launching Frameworks for Platforms Large and SmallVenue / Room: Hilton - Plaza ADate and Time:9/24/13, 18:30 - 19:15 This is a Birds Of a Feather (BOF) session by Hendrik Ebbers, Carl Dea, and me. The best thing about BOFs (for me) is that in addition to allowing us to share what we've been working on, it allows like-minded attendees to fully participate, asking questions, sharing ideas...more like a round table for the whole room to take part in. It's incredibly stimulating, and a lot of learning takes place for all involved. Session ID: TUT3676Session Title: Java Embedded Extreme Mashups: Building Self-Powering Sensor Nets for the Internet of ThingsVenue / Room: Hotel Nikko - Nikko Ballroom IDate and Time:9/24/13, 12:30 - 14:30 This is a two-hour tutorial where Jose Pereda and I take attendees through building a self-licking, renewable energy (RE) ice cream cone.  :-)  Renewable energy systems come in all shapes and sizes, and embedded systems - especially Java-driven ones - are excellent for monitoring those systems. Building remote sensor nets that not only monitor and report system status, but are also powered by those same RE systems, is inexpensive and straightforward once you have the right hardware and know-how. We cover everything from hardware to software, communication and optimization, with solutions that scale well from small personal systems to utility-sized deployments. And we have a good time doing it.  :-) So please, come join us! There's no better place to see what's happening in the world of Java than JavaOne. Hope to see you there! All the best, Mark

I'm excited to be able to speak at JavaOne again this year! Last year was an incredible experience, great brain food for anyone committed to Java and the Java ecosystem. This year promises to be even...

JavaDev

Secure Email from Java

I've been working recently with a client to do some rather useful things with notifications, and one of them involved sending a secure email from within a Java program. We encountered some interesting (translation: weird!) challenges, and in overcoming them, I worked out a reasonably straightforward path through the minefield. If you've been thinking about secure-email-enabling your Java app but aren't sure where to start, hopefully this will serve as a fairly quick and mostly painless primer.  :-) The Problem Let me first say that if you only want to send a plain-text email from Java, there are ways to do that without much fuss and without any external players. If you want to sign or encrypt your emails, though, you'll need a couple of extra components: 1. a digital certificate (private/public key pair issued by a recognized Certificate Authority, or "CA") and 2. a means of using the certificate to sign and/or encrypt the email The goal is to digitally sign an email to assure recipients that the sender of the mail is indeed me (or you, if you're following along at work/home). Let's get started! Getting Your Tools in Order Getting a Certificate First, we have to have a digital certificate. If you already have one, you can skip this step...but if not, StartSSL offers free user/email certificates for personal use. Just point your browser to the StartSSL site and click the large button labeled "Sign-up". You'll need to provide them some information, enter the verification code they email to the address you provide, and they do the rest...including installing your new cert and the certificate chain into your web browser. Freeing the Certificate from your Browser Perhaps the easiest way to use a certificate is to store it (keys, certificate chain) in a Java Keystore (jks). Extracting your shiny new certificate from your browser is a relatively easy (albeit drawn-out) process. From your browser, export your certificate, including private key. This will produce a .pfx file, which is a PKCS12 keystore. From Chrome, you simply: Click on the Wrench (or Lines) icon in the upper-right corner Select "Settings" from the menu "Show advanced settings..." at the bottom of the page Scroll down to the section labeled "HTTPS/SSL" Click the "Manage certificates..." button to display your certificates. Then, from the certificates window: Select the target certificate and click the "Export..." button Click "Next" from the Export Wizard window Choose "Yes, export the private key" and click "Next" Under the "Personal Information Exchange - PKCS #12 (.PFX)" entry, select the options to "Include all certificates in the certification path if possible" and "Export all extended properties" (NOTE: Do NOT choose to "Delete the private key if the export is successful". No no no!) and click "Next" Enter a password (twice) and click "Next" Provide a path/filename for the export and click "Next", and finally... Confirm the export options and click "Finish". Now that we've liberated your cert from the browser, let's make it usable by our (non-browser) Java program. Creating a Java Keystore The fastest, easiest way I've found to convert a .pfx file to a .jks (Java Keystore) file is with the Oracle 11g database client. The database client can be downloaded by following this link, selecting the "See All" link to the right of your listed operating system, and choosing the 11g client from the OS-specific download page. Once it's downloaded and installed, you're ready to proceed. Like the .pfx file, the Oracle wallet is a PKCS12 keystore, and the orapki utility (and other tools) included with the database client can be used to manipulate it...as long as it thinks it's dealing with an Oracle wallet. To make that happen, simply rename the .pfx file to ewallet.p12. Since we aren't dealing with the Oracle Wallet Manager, we don't have to worry about meeting OWM's password criteria or other niceties. Yes, that really is all there is to it! Now, to make a Java Keystore. To do that, you'll need to open a command prompt and do the following tasks: Create an ORACLE_HOME environment variable that points to the install location of the Oracle client Run the following command, pointing to the orapki utility under %ORACLE_HOME%\bin (in Windows) or $ORACLE_HOME/bin (Mac/Linux/UNIX): orapki wallet pkcs12_to_jks -wallet <wallet_directory> -pwd <wallet_password> -jksKeyStoreLoc <java_key_store_path_and_filename> -jksKeyStorepwd <jks_password> You should now have a brand new Java KeyStore! You can verify its contents with the OpenSSL keytool utility: keytool -list -keystore <java_key_store> Now that we have our credentials in order, on to the Java side of things! Building the Solution There are several Java libraries available that aid in signing and/or encrypting email. Of the non-commercial options I found, all use the Bouncy Castle Crypto API and libraries as their underpinnings. Bouncy Castle (BC) may have a funny name, but it's all business with regard to encryption. At a very high level, you need to do the following things to create/send a signed email: Provide the email "essentials": SMTP server host & port, email addresses (sender & receiver), a subject, content, and the sending user's password Add BC as a new crypto provider Retrieve the cert from your Java Keystore Create and sign the email using the BC API/libraries Send the email There is much more you can do of course, but these are the "must-haves". In preparation for developing our secure email module, I created a proof of concept (BCCrypTool) by marrying a Java email program I'd written previously and some BC sample code...code reuse at its lowest level, but still good for the environment. :-) What you see here in my GitHub repo is a bit of streamlined Java code that should be pretty easy to repurpose. Please feel free to take a copy and do just that, and if you make significant changes/improvements and are able and inclined to share them, please feel free to do that as well. Sharing is caring.  :-) A quick note on libraries. You'll need the following to make this work: From JavaMail: mail.jar If using Java older than SE 6, you'll also need the JavaBeans Activation Framework: activation.jar And from Bouncy Castle, the following: The BC provider library (bcprov-jdk15on-147.jar) The BC S/MIME library (bcmail-jdk15on-147.jar) The BC security library (bcpkix-jdk15on-147.jar) There are other BC libraries available here if you'd like to take things even further. All the best to you in your Java secure email adventures! Mark

I've been working recently with a client to do some rather useful things with notifications, and one of them involved sending a secure email from within a Java program. We encountered some interesting...

Hardware Hacking

Creating a Portable Java/JavaFX Rig using the Raspberry Pi

So you're a mobile/embedded Java developer who just can't get enough time with your devices? Need to get your JDK/JavaFX ARM fix on the go? It's easy and inexpensive to do just that with only a few essential parts:Raspberry PiAtrix Lapdock, which provides portable keyboard/video/mouse and power for the Raspberry Pi!A few cables and adapters (shown in videos, described in linked article below)SD card (8G or more, Class 6 or higher)Edimax EW-7811Un wi-fi adapterThat's all the hardware you'll need to make some serious, very portable ARM Java magic. Total cost was under $120 when I started this adventure; YMMV.  :-)There are a few differences between setting up the soft-float (SF) and hard-float (HF) versions of Raspbian, but this recent post covers the basics of getting an OS on the SD card for booting and configuring the Pi. The two key differences between SF and HF configuration to this point:Overclocking. HF Raspbian allows for easy overclocking from the raspi-config utility. A word of warning, though: The OS devs caution that the maximum overclocking setting has been known to corrupt SD cards, and I've found this to be the case several times. Stepping down one level to the next-to-fastest overclocking setting works a treat.Wi-fi configuration. SF Debian/Raspbian wi-fi configuration can be best accomplished using the instructions in the aforementioned post. Trying the same thing in HF Raspbian results in a message suggesting the use of the wi-fi graphical configuration tool...and it's even easier. With the Edimax, all I did was boot with both ethernet cable & Edimax connected, sudo su, startx, and run wpa_gui under the Internet menu (WiFi Config on the desktop if not root). Fill in your wi-fi details (I used WPA2/CCMP for my WAP) and then File|Save Configuration when finished. Quick, easy, and done.  :-)Below are links to a couple of short video tours of my mobile Java/JavaFX "testing rig". I'd embed them directly if the Roller blog software supported it (if someone knows how, please let me know!). After the video links is a link to an article/video I used as a template when I originally made mine. Great stuff, fun, and extremely useful...for me, anyway. Hope you enjoy it!Video 1: Intro to Raspberry Pi & Atrix Lapdock, Part 1 of 2Video 2: Follow-on to Raspberry Pi & Atrix Lapdock, Part 2 of 2Reference article/videoHappy hardware hacking,Mark

So you're a mobile/embedded Java developer who just can't get enough time with your devices? Need to get your JDK/JavaFX ARM fix on the go? It's easy and inexpensive to do just that with only a few...

Hardware Hacking

Prepping the Raspberry Pi for Java Excellence (part 1)

I've only recently been able to begin working seriously with my first Raspberry Pi, received months ago but hastily shelved in preparation for JavaOne. The Raspberry Pi and other diminutive computing platforms offer a glimpse of the potential of what is often referred to as the embedded space, the "Internet of Things" (IoT), or Machine to Machine (M2M) computing. I have a few different configurations I want to use for multiple Raspberry Pis, but for each of them, I'll need to perform the following common steps to prepare them for their various tasks: Load an OS onto an SD card Get the Pi connected to the network Load a JDK I've been very happy to see good friend and JFXtras teammate Gerrit Grunwald document how to do these things on his blog (link to article here - check it out!), but I ran into some issues configuring wi-fi that caused me some needless grief. Not knowing if any of the pitfalls were caused by my slightly-older version of the Pi and not being able to find anything specific online to help me get past it, I kept chipping away at it until I broke through. The purpose of this post is to (hopefully) help someone else recognize the same issues if/when they encounter them and work past them quickly. There is a great resource page here that covers several ways to get the OS on an SD card, but here is what I did (on a Mac): Plug SD card into reader on/in Mac Format it (FAT32) Unmount it (diskutil unmountDisk diskn, where n is the disk number representing the SD card) Transfer the disk image for Debian to the SD card (dd if=2012-08-08-wheezy-armel.img of=/dev/diskn bs=1m) Eject the card from the Mac (diskutil eject diskn) There are other ways, but this is fairly quick and painless, especially after you do it several times. Yes, I had to do that dance repeatedly (minus formatting) due to the wi-fi issues, as it kept killing the ability of the Pi to boot. You should be able to dramatically reduce the number of OS loads you do, though, if you do a few things with regard to your wi-fi. Firstly, I strongly recommend you purchase the Edimax EW-7811Un wi-fi adapter. This adapter/chipset has been proven with the Raspberry Pi, it's tiny, and it's cheap. Avoid unnecessary aggravation and buy this one! Secondly, visit this page for a script and instructions regarding how to configure your new wi-fi adapter with your Pi. Here is the rub, though: there is a missing step. At least there was for my combination of Pi version, OS version, and uncanny gift of timing and luck. :-) Here is the sequence of steps I used to make the magic happen: Plug your newly-minted SD card (with OS) into your Pi and connect a network cable (for internet connectivity) Boot your Pi. On the first boot, do the following things: Opt to have it use all space on the SD card (will require a reboot eventually) Disable overscan Set your timezone Enable the ssh server Update raspi-config Reboot your Pi. This will reconfigure the SD to use all space (see above). After you log in (UID: pi, password: raspberry), upgrade your OS. This was the missing step for me that put a merciful end to the repeated SD card re-imaging and made the wi-fi configuration trivial. To do so, just type sudo apt-get upgrade and give it several minutes to complete. Pour yourself a cup of coffee and congratulate yourself on the time you've just saved.  ;-) With the OS upgrade finished, now you can follow Mr. Engman's directions (to the letter, please see link above), download his script, and let it work its magic. One aside: I plugged the little power-sipping Edimax directly into the Pi and it worked perfectly. No powered hub needed, at least in my configuration. To recap, that OS upgrade (at least at this point, with this combination of OS/drivers/Pi version) is absolutely essential for a smooth experience. Miss that step, and you're in for hours of "fun". Save yourself! I'll pick up next time with more of the Java side of the RasPi configuration, but as they say, you have to cross the moat to get into the castle. Hopefully, this will help you do just that. Until next time! All the best,Mark

I've only recently been able to begin working seriously with my first Raspberry Pi, received months ago but hastily shelved in preparation for JavaOne. The Raspberry Pi and other diminutive computing...

JavaDev

MonologFX: FLOSS JavaFX Dialogs for the Taking

(UPDATED Nov 10 with simpler button icon API) Some time back, I was searching for basic dialog functionality within JavaFX and came up empty. After finding a decent open-source offering on GitHub that almost fit the bill, I began using it...and immediately began thinking of ways to "do it differently."  :-)  Having a weekend to kill, I ended up creating DialogFX and releasing it on GitHub (hecklerm/DialogFX) for anyone who might find it useful. Shortly thereafter, it was incorporated into JFXtras (jfxtras.org) as well. Today I'm sharing a different, more flexible and capable JavaFX dialog called MonologFX that I've been developing and refining over the past few months. The summary of its progression thus far is pretty well captured in the README.md file I posted with the project on GitHub: After creating the DialogFX library for JavaFX, I received several suggestions and requests for additional or different functionality, some of which ran counter to the interfaces and/or intent of the DialogFX "way of doing things". Great ideas, but not completely compatible with the existing functionality. Wanting to incorporate these capabilities, I started over...incorporating some parts of DialogFX into the new MonologFX, as I called it, but taking it in a different direction when it seemed sensible to do so. In the meantime, the OpenJFX team has released dialog code that will be refined and eventually incorporated into JavaFX and OpenJFX. Rather than just scrap the MonologFX code or hoard it, I'm releasing it here on GitHub with the hope that someone may find it useful, interesting, or entertaining. You may never need it, but regardless, MonologFX is there for the taking. Things of Note So, what are some features of MonologFX? Four kinds of dialog boxes: ACCEPT (check mark icon), ERROR (red 'x'), INFO (blue "i"), and QUESTION (blue question mark) Button alignment configurable by developer: LEFT, RIGHT, or CENTER Skins/stylesheets support Shortcut key/mnemonics support (Alt-<key>) Ability to designate default (RETURN-key) and cancel (ESCAPE-key) buttons Built-in button types and labels for OK, CANCEL, ABORT, RETRY, IGNORE, YES, and NO Custom button types: CUSTOM1, CUSTOM2, CUSTOM3 Internationalization (i18n) built in. Currently, files are provided for English/US and Spanish/Spain locales; please share others and I'll add them! Icon support for your buttons, with or without text labels Fully Free/Libre Open Source Software (FLOSS), with latest source code & .jar always available at GitHub Quick Usage Overview Having an intense distaste for rough edges and gears flying when things break (!), I've tried to provide defaults for everything and "fail-safes" to avoid messy outcomes if some property isn't specified, etc. This also feeds the goal of making MonologFX as easy to use as possible, while retaining the library's full flexibility. Or at least that's the plan.  :-) You can hand-assemble your buttons and dialogs, but I've also included Builder classes to help move that along as well. Here are a couple examples:         MonologFXButton mlb = MonologFXButtonBuilder.create()                .defaultButton(true)                .icon("/testmonologfx/dialog_apply.png")                .type(MonologFXButton.Type.OK)                .build();         MonologFXButton mlb2 = MonologFXButtonBuilder.create()                .cancelButton(true)                .icon("/testmonologfx/dialog_cancel.png")                .type(MonologFXButton.Type.CANCEL)                .build();         MonologFX mono = MonologFXBuilder.create()                .modal(true)                .message("Welcome to MonologFX! Please feel free to try it out and share your thoughts.")                .titleText("Important Announcement")                .button(mlb)                .button(mlb2)                .buttonAlignment(MonologFX.ButtonAlignment.CENTER)                .build();         MonologFXButton.Type retval = mono.showDialog(); MonologFXButton mlb = MonologFXButtonBuilder.create()        .defaultButton(true)        .icon("/testmonologfx/dialog_apply.png")        .type(MonologFXButton.Type.YES)        .build(); MonologFXButton mlb2 = MonologFXButtonBuilder.create()        .cancelButton(true)        .icon("/testmonologfx/dialog_cancel.png")        .type(MonologFXButton.Type.NO)        .build(); MonologFX mono = MonologFXBuilder.create()        .modal(true)        .type(MonologFX.Type.QUESTION)        .message("Welcome to MonologFX! Does this look like it might be useful?")        .titleText("Important Announcement")        .button(mlb)        .button(mlb2)        .buttonAlignment(MonologFX.ButtonAlignment.RIGHT)        .build(); MonologFXButton.Type retval = mono.showDialog(); Extra Credit Thanks to everyone who offered ideas for improvement and/or extension to the functionality contained within DialogFX. The JFXtras team welcomed it into the fold, and while I doubt there will be a need to include MonologFX in JFXtras, team members Gerrit Grunwald & Jose Pereda Llamas volunteered templates and i18n expertise to make MonologFX what it is. Thanks for the push, guys! Where to Get (Git!) It If you'd like to check it out, point your browser to the MonologFX repository on GitHub. Full source code is there, along with the current .jar file. Please give it a try and share your thoughts! I'd love to hear from you. All the best,Mark

(UPDATED Nov 10 with simpler button icon API)  Some time back, I was searching for basic dialog functionality within JavaFX and came up empty. After finding a decent open-source offering on GitHub that...

Blog Spotlight

Seven Random Thoughts on JavaOne

As most people reading this blog may know, last week was JavaOne. There are a lot of summary/recap articles popping up now, and while I didn't want to just "add to the pile", I did want to share a few observations. Disclaimer: I am an Oracle employee, but most of these observations are either externally verifiable or based upon a collection of opinions from Oracle and non-Oracle attendees alike. Anyway, here are a few take-aways: The Java ecosystem is alive and well, with a breadth and depth that is impossible to adequately describe in a short post...or a long post, for that matter. If there is any one area within the Java language or JVM that you would like to - or need to - know more about, it's well-represented at J1. While there are several IDEs that are used to great effect by the developer community, NetBeans is on a roll. I lost count how many sessions mentioned or used NetBeans, but it was by far the dominant IDE in use at J1. As a recent re-convert to NetBeans, I wasn't surprised others liked it so well, only how many. OpenJDK, OpenJFX, etc. Many developers were understandably concerned with the change of sponsorship/leadership when Java creator and longtime steward Sun Microsystems was acquired by Oracle. The read I got from attendees regarding Oracle's stewardship was almost universally positive, and the push for "openness" is deep and wide within the current Java environs. Few would probably have imagined it to be this good, this soon. Someone observed that "Larry (Ellison) is competitive, and he wants to be the best...so if he wants to have a community, it will be the best community on the planet." Like any company, Oracle is bound to make missteps, but leadership seems to be striking an excellent balance between embracing open efforts and innovating in competitive paid offerings. JavaFX (2.x) isn't perfect or comprehensive, but a great many people (myself included) see great potential, are developing for it, and are really excited about where it is and where it may be headed. This is another part of the Java ecosystem that has impressive depth for being so new (JavaFX 1.x aside). If you haven't kicked the tires yet, give it a try! You'll be surprised at how capable and versatile it is, and you'll probably catch yourself smiling while coding again.  :-) JavaEE is everywhere. Not exactly a newsflash, but there is a lot of buzz around EE still/again/anew. Sessions ranged from updated component specs/technologies to Websockets/HTML5, from frameworks to profiles and application servers. Programming "server-side" Java isn't confined to the server (as you no doubt realize), and if you still consider JavaEE a cumbersome beast, you clearly haven't been using the last couple of versions. Download GlassFish or the WebLogic Zip distro (or another JavaEE 6 implementation) and treat yourself. JavaOne is not inexpensive, but to paraphrase an old saying, "If you think that's expensive, you should try ignorance." :-) I suppose it's possible to attend J1 and learn nothing, but you'd have to really work at it! Attending even a single session is bound to expand your horizons and make you approach your code, your problem domain, differently...even if it's a session about something you already know quite well. The various presenters offer vastly different perspectives and challenge you to re-think your own approach(es). And finally, if you think the scheduled sessions are great - and make no mistake, most are clearly outstanding - wait until you see what you pick up from what I like to call the "hallway sessions". Between the presentations, people freely mingle in the hallways, go to lunch and dinner together, and talk. And talk. And talk. Ideas flow freely, sparking other ideas and the "crowdsourcing" of knowledge in a way that is hard to imagine outside of a conference of this magnitude. Consider this the "GO" part of a "BOGO" (Buy One, Get One) offer: you buy the ticket to the "structured" part of JavaOne and get the hallway sessions at no additional charge. They're really that good. If you weren't able to make it to JavaOne this year, you can still watch/listen to the sessions online by visiting the JavaOne course catalog and clicking the media link(s) in the right column - another demonstration of Oracle's commitment to the Java community. But make plans to be there next year to get the full benefit! You'll be glad you did. All the best,Mark P.S. - I didn't mention several other exciting developments in areas like the embedded space and the "internet of things" (M2M), robotics, optimization, and the cloud (among others), but I think you get the idea. JavaOne == brainExpansion;  Hope to see you there next year!

As most people reading this blog may know, last week was JavaOne. There are a lot of summary/recap articles popping up now, and while I didn't want to just "add to the pile", I did want to share a few...

JavaDev

Join Me at JavaOne!

JavaOne 2012 is less than a week away! If you've already made plans to be there, you're probably getting pretty excited about it already...and if not, what are you waiting for?!?Before I get to the session information, I want to point out that qualified students get free admission to JavaOne, so if you are (or know) a CS or IT (or other tech-leaning) student who might like to attend, follow the link and start making plans. There is so much there to learn and experience.I'm happy to say I'll be a small part of the festivities. I'll be leading the following session:CON3519 - Building Hybrid Cloud Apps: Local Databases + The Cloud = Extreme VersatilityIn this session, learn how to design and develop applications that leverage both local storage and the cloud, maximizing the strengths of each. Using NetBeans, JavaServer Faces 2.0, GlassFish Server technology, JavaFX 2, Oracle Database, and Evernote, rapidly create prototypical applications that can be deployed in various environments and scaled up/out with enterprise cloud solutions. As a contributor to the JFXtras project, I also hope to attend the following "Birds Of a Feather" (BOF) session led by Gerrit Grunwald and Stephen Chin:BOF5503 - JFXtras Super Happy Dev BOFJFXtras, the open source JavaFX control and extensions project, is back for JavaFX 2.0. In this session, you will learn about the latest changes in JFXtras 2.0, including new components, controls, and features that integrate with the JavaFX 2.0 libraries. Expect to meet the JFXtras core team members as well as other interesting client RIA implementers and developers. Now that JavaFX is coded in Java, a few server-side hackers may even be let in the door.If you're there, please stop by and introduce yourself! And to follow along with my J1 travels or keep in contact afterward, please follow me on Twitter or connect via G+ or Facebook (links in panel to right). Hope to see you there, but either way, keep the Java flowing!All the best,Mark 

JavaOne 2012 is less than a week away! If you've already made plans to be there, you're probably getting pretty excited about it already...and if not, what are you waiting for?!? Before I get to the...

JavaDev

DialogFX: A New Approach to JavaFX Dialogs

How would you like a quick and easy drop-in dialog box capability for JavaFX? That's what I was thinking when a weekend presented itself. And never being one to waste a good weekend...  :-) After doing some "roll-your-own" basic dialog building for a JavaFX app, I recently stumbled across Anton Smirnov's work on GitHub. It was a good start, but it wasn't exactly what I was after, and ideas just kept popping up of things I'd do differently. I wanted something a bit more streamlined, a bit easier to just "drop in and use". And so DialogFX was born. DialogFX wasn't intended to be overly fancy, overly clever - just useful and robust. Here were my goals: Easy to use. A dialog "system" should be so simple to use a new developer can drop it in quickly with nearly no learning curve. A seasoned developer shouldn't even have to think, just tap in a few lines and go. Why should dialogs slow "actual development"?  :-) Defaults. If you don't specify something (dialog type, buttons, etc.), a good dialog system should still work. It may not be pretty, but it shouldn't throw gears. Sharable. It's all open source. Even the icons are in the commons, so they can be reused at will. Let's take a look at some screen captures and the code used to produce them. DialogFX INFO dialog Screen captures Windows Mac  Sample code         DialogFX dialog = new DialogFX();        dialog.setTitleText("Info Dialog Box Example");        dialog.setMessage("This is an example of an INFO dialog box, created using DialogFX.");        dialog.showDialog(); DialogFX ERROR dialogScreen capturesWindowsMac Sample code         DialogFX dialog = new DialogFX(Type.ERROR);        dialog.setTitleText("Error Dialog Box Example");        dialog.setMessage("This is an example of an ERROR dialog box, created using DialogFX.");        dialog.showDialog();DialogFX ACCEPT dialogScreen capturesWindowsMac Sample code         DialogFX dialog = new DialogFX(Type.ACCEPT);        dialog.setTitleText("Accept Dialog Box Example");        dialog.setMessage("This is an example of an ACCEPT dialog box, created using DialogFX.");        dialog.showDialog();DialogFX Question dialog (Yes/No)Screen capturesWindowsMac Sample code         DialogFX dialog = new DialogFX(Type.QUESTION);        dialog.setTitleText("Question Dialog Box Example");        dialog.setMessage("This is an example of an QUESTION dialog box, created using DialogFX. Would you like to continue?");        dialog.showDialog(); DialogFX Question dialog (custom buttons)Screen capturesWindowsMac Sample code         List<String> buttonLabels = new ArrayList<>(2);        buttonLabels.add("Affirmative");        buttonLabels.add("Negative");         DialogFX dialog = new DialogFX(Type.QUESTION);        dialog.setTitleText("Question Dialog Box Example");        dialog.setMessage("This is an example of an QUESTION dialog box, created using DialogFX. This also demonstrates the automatic wrapping of text in DialogFX. Would you like to continue?");        dialog.addButtons(buttonLabels, 0, 1);        dialog.showDialog();A couple of things to noteYou may have noticed in that last example the addButtons(buttonLabels, 0, 1) call. You can pass custom button labels in and designate the index of the default button (responding to the ENTER key) and the cancel button (for ESCAPE). Optional parameters, of course, but nice when you may want them.Also, the showDialog() method actually returns the index of the button pressed. Rather than create EventHandlers in the dialog that really have little to do with the dialog itself, you can respond to the user's choice within the calling object. Or not. Again, it's your choice.  :-)And finally, I've Javadoc'ed the code in the main places. Hopefully, this will make it easy to get up and running quickly and with a minimum of fuss.How Do I Get (Git?) It?To try out DialogFX, just point your browser here to the DialogFX GitHub repository and download away! Please take a look, try it out, and let me know what you think. All feedback welcome!All the best,Mark 

How would you like a quick and easy drop-in dialog box capability for JavaFX? That's what I was thinking when a weekend presented itself. And never being one to waste a good weekend...  :-) After doing...

JavaDev

JavaFX Dialogs, Anyone?

A common question about JavaFX, especially for those coming from a Swing background, is "How do I do Dialogs?" The reason this is a question at all is that, currently, there is no baked-in capability to do dialog boxes within a pure JavaFX 2.x application. But come on...you wouldn't be reading about this at all if you weren't a resourceful programmer. You have ways of making things happen.  :-) I ran across a decent patch of code recently that handles many of the dialog chores for you. Pros and cons follow, but pointing your browser to this link on Github (appropriately named JavaFXDialog) will get you off to a good start. Here are some screen shots the original code author, Anton Smirnov, provided: Nothing fancy, just clean and functional. Now, about those pros and cons. From my perspective, here's the bottom line: Pros Already developed. Time required to implement is limited to downloading and decompressing the file, doing a bit of reading, and writing a few lines of code to try things out. Easy. Most of the work is done, and the interface is pretty simple. Open source. If you want to make changes - and I'm already thinking along those lines, so you may as well admit you will, too - you can do it. Cons Documentation. What you see on the Wiki page is the extent of it. Lack of activity. As of the date this article was published, the code hasn't been updated in several months...so the project is a bit stale. To be fair, the cons listed above won't cause anyone to lose sleep. After all, you don't expect constant revisions against something that works well enough for most purposes, and if your needs exceed what is there, it's easy to mod the code yourself or "roll your own" if you prefer. The lack of documentation isn't a show-stopper either due to the limited functionality and complexity of the code. Wrapping It Up If you need a quick, drop-in dialog capability for your JavaFX 2.x app, give it a try and see what you think. And if you're already using something you like, please share it as well! I'd love to hear from you, take a look at what you pass along, and maybe do a "dialog shoot-out" article in the future. So..what works for you?  :-) All the best,Mark

A common question about JavaFX, especially for those coming from a Swing background, is "How do I do Dialogs?" The reason this is a question at all is that, currently, there is no baked-in capability...

Blog Spotlight

How to Get Started (FAST!) With JavaFX 2 and Scene Builder

A question I hear all too often is "How do I get started with JavaFX and/or Scene Builder?" Like most tools/toolsets, there are as many ways to use these implements as there are developers...but shouldn't there be an easy way to "hit the ground running"? While casting about for an end-to-end example, demo, or video, I found a wealth of useful information, but I couldn't find anything that took someone from start to finish, quickly and easily. JavaFX is easy and fun. But don't take my word for it; let's give it a try! Before we begin, you'll need to visit this page to download and install all the necessary goodies. Click the download link to go to the current downloads page, then download and install JavaFX (NOTE: if you already have a JDK installed that includes JavaFX, you can omit this step), then download and install the JavaFX Scene Builder. Specific instructions for those steps are located on that page. Go ahead, I'll wait right here.  :-) Back now? Great! Let's get started! First, let's fire up Scene Builder just to make sure it works. If not, you'll want to revisit the installation instructions on the downloads page. Once that's working, we're ready to roll...assuming you're running NetBeans 7.2 or higher, of course. You are running NetBeans, right? If not, you owe it to yourself to download it - it's free, and as you're about to see, it's pretty amazing. NetBeans and Scene Builder are loosely-but-effectively integrated, and using both greatly simplifies things and makes your life easier. Okay, here's the fun part: we're going to actually create a simple JavaFX application, create/modify a window using Scene Builder, and successfully test it in under 15 minutes. Don't believe me? Buckle up friend, here we go! NetBeans We start this fun frenzy with NetBeans. Choose File, New Project, JavaFX, then JavaFX FXML Application. This creates a very simple JavaFX app that includes a main application class, a controller class to provide the actual backing logic for the window defined in Scene Builder, and the FXML file containing our window definition (XML) code. I used the name "EasyJavaFX" for our project. Here's a quick summary of these three files: EasyJavaFX.java contains the main application class. We won't really do anything with this class for this example, as its primary purpose in life is to load the window definition code contained in the FXML file and then show the main stage/scene. You'll keep the JavaFX terms straight with ease if you relate them to the theater: a platform holds a stage, which contains scenes. Simple. :-) SampleController.java is our controller class that provides the "brains" behind the graphical interface. If you open the SampleController, you'll see that it includes a property and a method tagged with @FXML. This tag enables the integration of the visual controls and elements you define using Scene Builder. Let's take a look at that next. Sample.fxml is the definition file for your sample window. You can right-click and Edit the filename in the tree to view the underlying XML - and you may need to do that if you change filenames or properties by hand - or you can double-click on it to open it in Scene Builder. Let's do that next, but first a quick look at our little project: Scene Builder Opening Sample.fxml in Scene Builder results in the display of a very spartan window. Let's rework it a little. For a complete tour of Scene Builder, please visit this page, but here's the nickel tour: stuff and navigation to the left, picture in the middle, and properties on the right. :-) We'll make some small modifications like so: First, we click on the Button in the Hierarchy panel (bottom left), which selects it in the middle Content panel. We'll move it down and over a bit to make room for another button. Next, let's drag another button from the Library panel and drop it onto the canvas, lining it up with the other button using the red positioning lines that appear while dragging it. Once the button is positioned, we turn our attention to the Properties panel. We'll assign our new button an fx:id of exitButton, change the text to Exit, and tab out of the field to see our changes dynamically applied. Next, we click on the other button to change its fx:id and text to clickmeButton and "Click Me for an Important Announcement", respectively. Finally, we click the Exit button and resize it to be a bit wider. Who likes to hunt for tiny Exit buttons? We're nearly done with our first round with Scene Builder. To finish, we select the Label in the Hierarchy panel at the bottom left - that's often the quickest way to locate "hidden" visual controls - and then resize it using the sizing handles on the canvas, again using the red lines to line up with edges and buttons. Once we're done, things should look something like this: Click File, Save to save our changes, and Scene Builder confirms with a brief message at the top of the Content panel. Leaving Scene Builder open for convenience, return to NetBeans for the next step. Back to NetBeans Let's make a few changes to the controller class. Opening SampleController.java, let's start with the only method we (currently) have. Since we now have two buttons, we will need to keep two methods straight. Renaming handleButtonAction to something like handleClickmeButtonAction is a good start. And to add something of significance to read when the button is clicked, we'll replace the wonderfully traditional "Hello World!" with "Space... the Final Frontier. These are the voyages of the starship Enterprise. Its continuing mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no one has gone before." For those reading this who aren't Star Trek fans, please feel free to substitute your own, slightly less-interesting text.  :-) Next, we'll create a method for our Exit button by either copying the other method and renaming it or hand-jamming it. Either way, be sure you have the @FXML tag to allow for integration with our window definition/Scene Builder. Putting the following line in our new handleExitButtonAction method will give us a quick escape hatch for our demo app: Platform.exit(); To fix the error shown by NetBeans, click on the light bulb to the left of the code line and allow it to import javafx.application.Platform. After a quick click on the Save All button, we're good to go from the NetBeans side. Now to go back to Scene Builder to wrap things up. And Back to Scene Builder In order for our buttons to tie to our new methods, we need to connect them to the names we gave those methods in our SampleController class. First, we'll select the top Button (clickmeButton) in the Hierarchy panel. Next we turn our attention to the Properties panel on the right. At the bottom of the right side is a collapsed section labeled "Code: Button". Clicking that line opens the Code properties window so we can update the OnAction property. Notice it still points to the method formerly known as handleButtonAction. Click the dropdown, select handleClickmeButtonAction, tab out of the field, and we're done with that button. We repeat some of the same steps with the other (Exit) button, although since we already have the Code properties panel open, selecting the button takes us directly there. Choosing handleExitButtonAction from its OnAction dropdown and tabbing out of the field concludes our work with Exit. But there is one more thing, purely cosmetic though it may be... Since we added quite a lot of text to our label (see the handleClickmeButton method in the SampleController class), we may want to change the default behavior of our display label. Labels default to using an ellipsis when the length of text to display exceeds the space available, but we want to see the text in its entirety! Clicking the "Wrap" checkbox in the label's Properties panel fixes that up nicely and concludes our work in Scene Builder. Click File, Save, and then back to NetBeans for our maiden voyage! And Now Back to NetBeans for the Big Finale! Right-clicking the project in the Projects window to the left and clicking Run provides these satisfying results: Clicking the "Click Me" button displays the following: And clicking the Exit button closes the application. Start to finish, you just developed a JavaFX application using Scene Builder in less time than it takes to drink a cup of coffee...while learning your way around in the process. Fast, fun, and productive: THAT is JavaFX. All the best,Mark P.S. - There isn't much to the code, but I'll post it to GitHub if anyone wants it. Just let me know. P.P.S. - If there is any interest in a video, please let me know that as well by commenting below. No promises, but if enough people ask and I can find some free time...

A question I hear all too often is "How do I get started with JavaFX and/or Scene Builder?" Like most tools/toolsets, there are as many ways to use these implements as there are developers...but...

NetBeans

NetBeans (team) Responsiveness

When was the last time logging a potential bug/issue for any piece of software, with any vendor, was a pleasure? Most of us rank that with paying taxes, root canals, and visiting in-laws. :-)Not so with NetBeans. I logged a possible bug report one morning...and by the next morning, it had been assigned, analyzed, and an explanation and workaround posted while code changes and testing take place. In fewer than 24 hours, it effectively went from start to finish from an end-user developer perspective. That may not always be possible, but it speaks very well for the level of commitment of the NetBeans team.In addition to all the other things I appreciate about NetBeans, such as GlassFish integration/management, superb code generation, polished look-and-feel, ease of navigation, and many other things large and small, add excellent community support/dev engagement to the list. After using other IDEs for years, I could hardly be more pleased.Those who haven't logged many tool issues may not fully understand this post, but it can be a big deal...and usually at the most inopportune times...  :-)All the best,MarkDon't take my word for it, get your own! Visit the NetBeans site to download and check it out for yourself.(Disclaimer: I work for Oracle, but not on the NetBeans team. I'm just another (very) satisfied user.)

When was the last time logging a potential bug/issue for any piece of software, with any vendor, was a pleasure? Most of us rank that with paying taxes, root canals, and visiting in-laws. :-) Not so...

Blog Spotlight

Quick Fix for GlassFish/MySQL NoPasswordCredential Found

Just the other day, I stood up a GlassFish 3.1.2 server in preparation for a new web app we've developed. Since we're using MySQL as the back-end database, I configured it for MySQL (driver) and created the requisite JDBC resource and supporting connection pool. Pinging the finished pool returned a success, and all was well.Until we fired up the app, that is -- in this case, after a weekend. Funny how things seem to break when you leave them alone for a couple of days. :-) Strangely, the error indicated "No PasswordCredential found". Time to re-check that pool.All the usual properties and values were there (URL, driverClass, serverName, databaseName, portNumber, user, password) and were populated correctly. Yes, the password field, too. And it had pinged successfully. So why the problem?A bit of searching online produced enough relevant material to offer promise. I didn't take notes as I was investigating the cause (note to self), but here were the general steps I took to resolve the issue:First, per some guidance I had found, I tried resetting the password value to nothing (using () for a value). Of course, this didn't fix anything; the database account requires a password. And when I tried to put the value back, GlassFish politely refused. Hmm.I'd seen that some folks created a new pool to replace the "broken" one, and while that did work for them, it seemed to simply side-step the issue. So I deleted the password property - which GlassFish allowed me to do - and restarted the domain. Once I was back in, I re-added the password property and its value, saved it, and pinged...success! But now to the app for the litmus test.The web app worked, and everything and everyone was now happy. Not bad for a Monday.  :-DHope this helps,Mark

Just the other day, I stood up a GlassFish 3.1.2 server in preparation for a new web app we've developed. Since we're using MySQL as the back-end database, I configured it for MySQL (driver) and...

Profile of the Cool

Looking Through the Telescope From the Big End: Four Small Java Developments that Pack a Punch!

There are a LOT of exciting developments in Java, almost on a daily basis. Most of them make a big splash, and for good reason! But sometimes, it's the little things... There have been a lot of small developments in Java that are pretty exciting, too. I'll pick out four of my favorites - each at a different level and/or stage of development or detail - and explain why they're a big deal. Let's get started! Home automation I had the privilege of watching Vinicius and Yara Senger give a presentation at Jfokus (available below at Parleys.com) on Java EE and home automation. The Sengers developed the jHome platform and run it on GlassFish, controlling Arduino-based appliances in their home, office, and boat. I won't give away all the spoilers, and it isn't Java end-to-end...but the Sengers are demonstrating a compelling, fully open source (hardware and software!) package for Java working in harmony with even the tiniest of devices. Video presentation: Having Fun with Home Automation and Java EE PDF file of presentation Robotics FIRST, or "For Inspiration and Recognition of Science and Technology", was founded by world-renowned inventor Dean Kamen. In his words: "Our mission is to inspire young people to be science and technology leaders, by engaging them in exciting mentor-based programs that build science, engineering and technology skills, that inspire innovation, and that foster well-rounded life capabilities including self-confidence, communication, and leadership." FIRST's vehicle for doing this is robotics. Teams of various ages use available technology components and their brains to develop and program robots to compete in some pretty tricky challenges. This isn't Robot Wars (no Real Steel destructive matches here), but it's just as engaging - for the teams and spectators alike. The 2012 FIRST International Championship was held in St. Louis, MO, USA, and teams representing several countries participated. I was able to attend for awhile - with an event like this, you just can't see it all! - and chanced upon a team in the pit area with a homemade sign saying "We use JAVA!". I was directed to the 15 year-old programmer who proudly informed me that they use NetBeans and Java to program their robot. We had a nice conversation, and I was left with the realization that Java's original "embedded" mission is still being realized in ways that we don't often think about. 2012 FIRST Championship Results Page Raspberry Pi Simon Ritter recently posted about his work with the Raspberry Pi and JavaFX 2. I had seen others relate their victories getting OpenJDK onto the little Pi, a small-but-capable computer the size of a deck of cards...but Simon (and those who provided assists in whatever form) took the bar and threw it up onto the roof. It won't win any supercomputer awards (well, not alone anyway!), but the Raspberry Pi's small size and low price now make a host of formerly-unrealistic uses possible. Even before much optimization is done, JavaFX 2 is already running. If you've ever migrated existing software (of any kind) to a new platform, you know that that first "clean" run can be elusive. I can't wait to see how far we can take this...just as I can't wait for my pre-ordered Pi to hurry up and get here! JavaFX on the Raspberry Pi Harmonization of Java ME, SE Henrik Stahl was on the Java Spotlight podcast recently (link below) presenting a clear vision for the harmonization of Java Micro Edition (ME) and Standard Edition (SE). The devil is in the details, of course, but here's the good news: 1) There is a plan2) The plan makes sense3) The plan is being worked...diligently! Without getting into those details or the challenges surrounding them (API synchronization, Jigsaw, etc.), a modern, consistent set of APIs and a modular architecture should excite Java developers wherever they may fall along the spectrum. Java Spotlight Episode 81: Henrik Stahl on Java 7 update 4 The Bottom Line It's an exciting time to work with Java at any level, and that includes in the crevices where small and/or embedded devices often lie hidden from view. If you haven't already been involved in "Java in the small", check it out. And if you have a favorite I've missed, drop me a line or comment below! If you like it, chances are the rest of us will, too.  :-) All the best,Mark &amp;amp;amp;amp;amp;amp;amp;lt;/span&amp;amp;amp;amp;amp;amp;amp;gt; height: 20px; &amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;gt;

There are a LOT of exciting developments in Java, almost on a daily basis. Most of them make a big splash, and for good reason! But sometimes, it's the little things... There have been a lot of smalldev...

JavaDev

Performance Test: DriverManager vs. DataSource

I was troubleshooting some well-traveled Java code the other day and hit an intriguing set of circumstances. The original developer(s) of this code -- a web application using JSP/servlets -- had written a data wrapper construct using DriverManager. After several upgrades of JDK and JVM, some minor cracks were starting to show. We tried doing a direct transplant of DataSource-based code into the wrapper mechanism, effectively a one-for-one swap of the minimum number of lines of code without any real refactoring. Yes, I know...not a good idea for the long-term. But one has to start somewhere.  :-) Interestingly, performance tanked. When things like that happen, it's time to get curious and dig deeper. Why DataSource? The DataSource approach to data connectivity brings numerous benefits with it (connection pooling, distributed transactions, etc.), but does it also carry a hefty performance penalty? I had never heard that it did. Either way, it's always good to do a little first-person testing to verify/refute findings. So off we go! Testing Methodology I put together a pretty simple test and ran it several times to factor out normal variations in environmental conditions. Using NetBeans, I created a plain-vanilla web application, sans frameworks. Next, I asked NetBeans to generate JPA entities from some tables in our database, and then an EJB (see this recent article for a refresher on connecting a basic EJB to underlying data via a DataSource) to provide the DataSource-based baseline. I then created an EJB that used DriverManager to build a connection and SQL statements for comparison. Oh, and one last necessity: I created a couple methods to capture start/stop times using System.currentTimeMillis() for a timekeeper. That covered all the essentials. And the Winner Is... Well, there really wasn't a runaway winner strictly from a performance perspective. Results varied from run to run, but these two horses were neck and neck, often trading the lead by only a few milliseconds in consecutive runs...which is great news, considering that DataSource offers so much more and yet manages to retain the expected level of performance. The bad news? Well, it's clear I have a lot of rework to do on this old code. Sigh.  :-) For more fun with Java, click here to follow Mark on Twitter.

I was troubleshooting some well-traveled Java code the other day and hit an intriguing set of circumstances. The original developer(s) of this code -- a web application using JSP/servlets -- had...

NetBeans

How to Plug a Small Hole in NetBeans JSF (Join Table) Code Generation

I was asked recently to provide an assist with designing and building a small-but-vital application that had at its heart some basic CRUD (Create, Read, Update, & Delete) functionality, built upon an Oracle database, to be accessible from various locations. Working from the stated requirements, I fleshed out the basic application and database designs and, once validated, set out to complete the first iteration for review. Using SQL Developer, I created the requisite tables, indices, and sequences for our first run. One of the tables was a many-to-many join table with three fields: one a primary key for that table, the other two being primary keys for the other tables, represented as foreign keys in the join table. Here is a simplified example of the trio of tables: Once the database was in decent shape, I fired up NetBeans to let it have first shot at the code. NetBeans does a great job of generating a mountain of essential code, saving developers what must be millions of hours of effort each year by building a basic foundation with a few clicks and keystrokes. Lest you think it (or any tool) can do everything for you, however, occasionally something tosses a paper clip into the delicate machinery and makes you open things up to fix them. Join tables apparently qualify.  :-) In the case above, the entity class generated for the join table (New Entity Classes from Database) included an embedded object consisting solely of the two foreign key fields as attributes, in addition to an object referencing each one of the "component" tables. The Create page generated (New JSF Pages from Entity Classes) worked well to a point, but when trying to save, we were greeted with an error: Transaction aborted. Hmm. A quick debugger session later and I'd identified the issue: when trying to persist the new join-table object, the embedded "foreign-keys-only" object still had null values for its two (required value) attributes...even though the embedded table objects had populated key attributes. Here's the simple fix: In the join-table controller class, find the public String create() method. It will look something like this:     public String create() {        try {            getFacade().create(current);            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("JoinEntityCreated"));            return prepareCreate();        } catch (Exception e) {            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));            return null;        }    } To restore balance to the force, modify the create() method as follows (changes in red):     public String create() {         try {            // Add the next two lines to resolve:            current.getJoinEntityPK().setTbl1id(current.getTbl1().getId().toBigInteger());            current.getJoinEntityPK().setTbl2id(current.getTbl2().getId().toBigInteger());            getFacade().create(current);            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("JoinEntityCreated"));            return prepareCreate();        } catch (Exception e) {            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));            return null;        }    } I'll be refactoring this code shortly, but for now, it works. Iteration one is complete and being reviewed, and we've met the milestone. Here's to happy endings (and customers)! All the best,Mark

I was asked recently to provide an assist with designing and building a small-but-vital application that had at its heart some basic CRUD (Create, Read, Update, & Delete) functionality, built upon an...

JavaDev

NetBeans, JSF, and MySQL Primary Keys using AUTO_INCREMENT

I recently had the opportunity to spin up a small web application using JSF and MySQL. Having developed JSF apps with Oracle Database back-ends before and possessing some small familiarity with MySQL (sans JSF), I thought this would be a cakewalk. Things did go pretty smoothly...but there was one little "gotcha" that took more time than the few seconds it really warranted. The Problem Every DBMS has its own way of automatically generating primary keys, and each has its pros and cons. For the Oracle Database, you use a sequence and point your Java classes to it using annotations that look something like this: @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="POC_ID_SEQ") @SequenceGenerator(name="POC_ID_SEQ", sequenceName="POC_ID_SEQ", allocationSize=1) Between creating the actual sequence in the database and making sure you have your annotations right (watch those typos!), it seems a bit cumbersome. But it typically "just works", without fuss. Enter MySQL. Designating an integer-based field as PRIMARY KEY and using the keyword AUTO_INCREMENT makes the same task seem much simpler. And it is, mostly. But while NetBeans cranks out a superb "first cut" for a basic JSF CRUD app, there are a couple of small things you'll need to bring to the mix in order to be able to actually (C)reate records. The (RUD) performs fine out of the gate. The Solution Omitting all design considerations and activity (!), here is the basic sequence of events I followed to create, then resolve, the JSF/MySQL "Primary Key Perfect Storm": Fire up NetBeans. Create JSF project. Create Entity Classes from Database. Create JSF Pages from Entity Classes. Test run. Try to create record and hit error. It's a simple fix, but one that was fun to find in its completeness. :-) Even though you've told it what to do for a primary key, a MySQL table requires a gentle nudge to actually generate that new key value. Two things are needed to make the magic happen. First, you need to ensure the following annotation is in place in your Java entity classes: @GeneratedValue(strategy = GenerationType.IDENTITY) All well and good, but the real key is this: in your controller class(es), you'll have a create() function that looks something like this, minus the comment line and the setId() call in bold red type:     public String create() {         try {             // Assign 0 to ID for MySQL to properly auto_increment the primary key.             current.setId(0);             getFacade().create(current);             JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CategoryCreated"));             return prepareCreate();         } catch (Exception e) {             JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));             return null;         }     } Setting the current object's primary key attribute to zero (0) prior to saving it tells MySQL to get the next available value and assign it to that record's key field. Short and simple…but not inherently obvious if you've never used that particular combination of NetBeans/JSF/MySQL before. Hope this helps! All the best, Mark UPDATE: Please see this follow-on article for a bit of clarification with regard to "why". Hint: It has to do with bean validation... ;) 

I recently had the opportunity to spin up a small web application using JSF and MySQL. Having developed JSF apps with Oracle Database back-ends before and possessing some small familiarity with MySQL...

Blog Spotlight

Spotlight on mkyong

Occasionally, I'd like to share a blog I've discovered or that someone has passed along to me. Criteria are few, but in a nutshell, it must be: Java-related. (Doh!) Interesting. A good blog is exciting to read at some level, whether due to perspective, eye-catching writing, or technical insight. It doesn't have to read like a Stephen King novel, but it should grab you somehow. Technically deep or technically broad. A site that dives deeply, quickly is a great reference for particular topics/tasks. On the other hand, one that covers a lot of ground at a high-but-still-technical level can be a handy site to visit occasionally as well. Both are what I consider "bookmarkable", but for different reasons. Drumroll, please... With that in mind, this Blog Spotlight is cast upon mkyong.com, a site I stumbled across that offers a little bit of everything for various Java dev audiences. The title indicates the site is for "Java web development tutorials", and indeed it does have these: JSF, Spring, Struts, Hibernate, JAX-WS, JAX-RS, and numerous other topics are addressed to varying degrees. The site isn't devoted exclusively to server-side tutorials, though. Recent posts include mobile development topics, and the links at the bottom of the page connect you to reference pages and other useful sites. I've poked around through a couple of the tutorials and, while they won't take you from "zero to hero", they do seem to provide a nice overview of the subject at hand. They also offer an occasional explanatory comment that is missing from far too many texts, sites, and doc pages. It's not a perfect site, but I like it. The Bottom Line mkyong.com offers a nice "summary site" of server-side tutorials, mobile dev posts, and reference links. Check it out! All the best,Mark 

Occasionally, I'd like to share a blog I've discovered or that someone has passed along to me. Criteria are few, but in a nutshell, it must be: Java-related. (Doh!) Interesting. A good blog is exciting...

Oracle

Integrated Cloud Applications & Platform Services