weblogs from Javablogs.com
The Week of Spring and Big Data and 50% discounts at manning.com
We’re excited to launch "The Week of Spring", a joint effort with Springsource.org and Manning Publications where we highlight a new book each day that is special to us and hand-picked by the Spring team. We also collaborated with Springsource to select a second book for each day of the week, from the Big Data Stack and will be offering those choices at a 50% discount only at manning.com! We hope you enjoy the deals!
Here’s the schedule for our Week of Spring discounts!
June 17: DAY ONE: Spring in Action, Fourth Edition and Big Data
Discount Code: sprwkd1 (exp. 6/18, 12 midnight EST)
June 18: DAY TWO: RabbitMQ in Action and Hadoop in Practice
Discount Code: sprwkd2 (exp. 6/19, 12 midnight EST)
June 19: DAY THREE: Spring Integration in Action and Redis in Action
Discount Code: sprwkd3 (exp. 6/20, 12 midnight EST)
June 20: DAY FOUR: Spring in Practice and Hadoop in Action
Discount Code: sprwkd4 (exp. 6/21, 12 midnight EST)
June 21: DAY FIVE: Spring Batch in Action and Solr in Action
Discount Code: TBA
June 22: DAY SIX: AspectJ in Action, Second Editionand Neo4J in Action
Discount Code: TBA
June 23: DAY SEVEN: 50% off all titles on Promotion
Discount Code: TBA
Java EE 7 Live Launch Provides Information and Interaction; Up Next: Virtual Developer Day

Last week, I attended the global live launch of Java EE 7, a webcast I wrote about earlier, titled "Introducing Java EE 7." The live webcast happened twice (on at 17:00 GMT on June 12, and 12 hours later at 05:00 GMT on June 13), thus enabling every Java developer in the world to attend the live session at some point during non-sleeping hours.
The value of attending the live sessions was the capability to participate interactively, via the chat app that was part of the webcast user interface:
But even if you weren't able to attend one of the live webcasts, if you registered for the event, you can still revisit pretty much everything that happened in the live webcasts, including reading the chat logs:
Now in progress: Virtual Developer Day
As I finish writing this post (about 17:00 GMT on June 19), I'm listening in on the latest Java Virtual Developer Day, titled Taking Java EE, SE, and Embedded to the Edge. This four-hour event started with a keynote address that provided an overview of Oracle's overall Java strategy. Now the breakout sessions are underway. Like the Java EE 7 launch webcast, there will be two editions of the Virtual Developer Day, timed so that Java developers around the world have an opportunity to attend at least one of the sessions during non-sleeping hours. The second VDD will happen at 08:00 GMT on June 25.
Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed.
-- Kevin Farnham (@kevin_farnham)
What’s our Status?
In “What’s our Status?” Dirk muses on how red and green status lights don’t really help you to fully understand the status of a complex system. He may not have a solution but instead calls for ideas in the hope that it will help get a discussion going.
Part of my day job is to watch over our Jenkins, which is controlling the build system that builds our software for a variety of different platforms. Therefore, people often come to me and ask: “What’s our status?” By which they mean: “Is everything working? And if it isn’t, can you give me a quick summary?”
I found that it’s really hard to answer this supposedly simple question; and I think it has to do with the traffic light metaphor that we’re using to visualise the status of our systems.
Let me explain. Cultural differences aside, we usually use a green light to indicate that everything is okay and a red light to signal that something is wrong. That works for a simple system where green equals that it works whereas red means that it doesn’t.
But what about a more complex system that consists of several subsystems? If you have 9 subsystems and 3 of them are red – what’s the status of the entire system? The convention is that the aggregated state of such a system is the “worst” of the states of the subsystems; so in our example, it would be red. While that correctly indicates that there is a problem, it may cause unnecessary panic in some circumstances.
What we are missing is a way to visualise (and verbalise) a status that’s somewhere in between red and green. I’ve been discussing this problem with a variety of people, including members of the Jenkins community, over the years. I’ve seen some interesting suggestions. For example, you could put all the status information of all the subsystems on one screen. You won’t be able to immediately comprehend the details but it will at least give you an idea of the overall status; something along the lines of “it’s not okay, but not so bad either”. Actually, you could simplify this visualisation and replace it with a simple red/green bar graph and maybe even stick a percentage value on to it.
Most suggestions assume that all the systems we are monitoring are equal. In practice, however, that’s often not the case. Where I work, for example, 60% of our customers are on Windows. Which means that the status of the Windows systems is more important than the status of one of the more exotic systems that we also support. One idea to compensate for that was to make the important systems bigger in a visualisation, but that doesn’t really scale. When you have 26 different configurations to monitor and visualise, you can’t really tell them apart any more.
So, maybe we need to take a step back and look at the problem from a different perspective. Who’s actually asking the question, “What’s our status?”
There’s my boss, for example. When he comes to me and asks “What’s our status?”, he’s really only interested in the high-level view of things. He would need to know if the Windows systems aren’t working, since they are important and he’s probably going to get calls from angry customers soon. He’s less concerned about the more exotic systems. He’d say “Just fix it” – and switch to more important things.
On the other hand, when someone from support comes to me, they usually have a very specific request. They have a ticket open with a customer who’s on Solaris 10 on SPARC, 64 bit, and they are really only interested in that specific system now. They don’t care if the Windows build isn’t working, since that’s not what the customer is using. So that’s a very different view of the system.
Then there’s the system administrator’s perspective, i.e. my perspective. I’m not really interested in things that work; I’m interested in things that don’t work. But I’d still like to get them in an order that tells me which ones to address first. Again, a completely different view of the system.
So I guess what I’m trying to say is this: There is no “one solution”. We need something more flexible, that can be adapted to the requirements of all these different users. It also makes me wonder if we’re trying to reinvent the wheel here. If we look at other industries – manufacturing, power plants, etc. – they often have complex systems that consist of many subsystems. Surely they must have had the same problem? So maybe someone out there in some other industry has already solved that problem and we simply don’t know about it.
Which is where you come in. Have you ever seen or heard about such a solution? I’d be very interested to hear about it! Please feel free to leave a comment below or contact me directly. Thank you.
You can purchase Dirk Haun’s ebook ‘Presenting for Geeks’ over on the Developer.Press website: http://developerpress.com/en/presenting
To find out more about Dirk you can contact him via:
dirk@haun-online.de
@dirkhaun
http://www.themobilepresenter.com
Posting or Deleting a Status Update with Redis

Posting or Deleting a Status Update with Redis
By Josiah L. Carlson, author of Redis in Action
In this article, based on chapter 8 of Redis in Action, author Josiah Carlson explains talks about Twitter user and status objects, which are the basis of almost all of the information in our application, and then deleting posts, which involves manipulating followers/following lists. Save 42% on Redis in Action with Promotional Code redlaujn, only at manning.com.
One of the most fundamental operations on a service like Twitter is posting status messages. People post to share their ideas, and people read because they're interested in what's going on with others. We'll first show you how to create a status message as a prerequisite for knowing the types of data that we'll be storing, and the we will show you how to get that status message into a profile timeline or the home timeline of the user's followers.
Status messages
While user profiles store information about an individual, the ideas that people are trying to express are stored in status messages. As was the case with user information, we'll store status message information inside a HASH.
In addition to the message itself, we'll store when the status message was posted, the user ID and login of the user who posted it (so that if we have a status object, we don't need to fetch the user object of the poster to discover their login name), and any additional information that should be stored about the status message. Figure 1 shows an example status message.
Figure 1 Example status message stored in a HASH
And that's everything necessary for a basic status message. The code to create such a status message can be seen in the next listing.
Listing 1 How to create a status message HASH
def create_status(conn, uid, message, **data): pipeline = conn.pipeline(True) pipeline.hget('user:%s'%uid, 'login') #1 pipeline.incr('status:id:') #2 login, id = pipeline.execute()
if not login: #3 return None
data.update({ 'message': message, #4 'posted': time.time(), 'id': id, 'uid': uid, 'login': login, }) pipeline.hmset('status:%s'%id, data) pipeline.hincrby('user:%s'%uid, 'posts') #5 pipeline.execute() return id #6
#1 Get the user's login name from their user ID.
#2 Create a new ID for the status message.
#3 Verify that we have a proper user account before posting.
#4 Prepare and set the data for the status message.
#5 Record the fact that a status message has been posted.
#6 Return the ID of the newly created status message.
There isn't anything surprising going on in the status creation function. The function fetches the login name of the user, gets a new ID for the status message, and then combines everything together and stores it as a HASH.
We'll now talk about making the status message visible to followers.
Updating the status
In this section, we'll discuss what happens to a status message when it's posted so it can find its way into the home timelines of that user's followers. We'll also talk about how to delete a status message.
You already know how to create the status message itself, but we now need to get the status message ID into the home timeline of all of our followers. How we should perform this operation will depend on the number of followers that the posting user happens to have. If the user has a relatively small number of followers (say, up to 1,000 or so), we can update their home timelines immediately. But for users with larger number of followers (like 1 million, or even the 25 million that some users have on Twitter), attempting to perform those insertions directly will take longer than is reasonable for a user to wait.
To allow for our call to return quickly, we'll do two things. First, we'll add the status ID to the home timelines of the first 1,000 followers as part of the call that posts the status message. Based on statistics from a site like Twitter, that should handle at least 99.9% of all users who post (Twitter-wide analytics suggest that there are roughly 100,000 to 250,000 users with more than 1,000 followers, which amounts to roughly 0.1% of the active user base). This means that only the top 0.1% of users will need another step.
Second, for those users with more than 1,000 followers, we'll start a deferred task. The next listing shows the code for pushing status updates to followers.
Listing 2 Update a user's profile timeline
def post_status(conn, uid, message, **data): id = create_status(conn, uid, message, **data) #1 if not id: #2 return None
posted = conn.hget('status:%s'%id, 'posted') #3 if not posted: #4 return None
post = {str(id): float(posted)} conn.zadd('profile:%s'%uid, **post) #5
syndicate_status(conn, uid, post) #6 return id
#1 Create a status message using the earlier function.
#2 If the creation failed, return.
#3 Get the time that the message was posted.
#4 If the post wasn't found, return.
#5 Add the status message to the user's profile timeline.
#6 Actually push the status message out to the followers of the user.
Notice that we broke our status updating into two parts. The first part calls the create_status() function from listing 1 to actually create the status message, and then adds it to the poster's profile timeline. The second part actually adds the status message to the timelines of the user's followers, which can be seen next.
Listing 3 Update a user's followers' home timelines
POSTS_PER_PASS = 1000 #1 def syndicate_status(conn, uid, post, start=0): followers = conn.zrangebyscore('followers:%s'%uid, start, 'inf', #2 start=0, num=POSTS_PER_PASS, withscores=True)
pipeline = conn.pipeline(False) for follower, start in followers: #3 pipeline.zadd('home:%s'%follower, **post) #4 pipeline.zremrangebyrank( 'home:%s'%follower, 0, -HOME_TIMELINE_SIZE-1) pipeline.execute()
if len(followers) >= POSTS_PER_PASS: #5 execute_later(conn, 'default', 'syndicate_status', [conn, uid, post, start])
#1 Only send to 1000 users per pass.
#2 Fetch the next group of 1000 followers, starting at the last person to be updated last time.
#3 Iterating through the followers results will update the "start" variable, which we can later pass on to subsequent syndicate_status() calls.
#4 Add the status to the home timelines of all of the fetched followers, and trim the home timelines so they don't get too big.
#5 If at least 1000 followers had received an update, execute the remaining updates in a task.
This second function is what actually handles pushing status messages to the first 1,000 followers' home timelines, and starts a delayed task using an API for followers past the first 1,000. With those new functions, we've now completed the tools necessary to actually post a status update and send it to all of a user's followers.
Exercise: Updating lists
In the last section, I suggested an exercise to build named lists of users. Can you extend the syndicate_message() function to also support updating the list timelines from before?
Let's imagine that we posted a status message that we weren't proud of; what would we need to do to delete it?
It turns out that deleting a status message is pretty easy. Before returning the fetched status messages from a user's home or profile timeline in get_messages(), we're already filtering "empty" status messages with the Python filter() function. So to delete a status message, we only need to delete the status message HASH and update the number of status messages posted for the user. The function that deletes a status message is shown in the following listing.
Listing 4 A function to delete a previously posted status message
def delete_status(conn, uid, status_id): key = 'status:%s'%status_id lock = acquire_lock_with_timeout(conn, key, 1) #1 if not lock: #2 return None
if conn.hget(key, 'uid') != str(uid): #3 return None
pipeline = conn.pipeline(True) pipeline.delete(key) #4 pipeline.zrem('profile:%s'%uid, status_id) #5
pipeline.zrem('home:%s'%uid, status_id) #6 pipeline.hincrby('user:%s'%uid, 'posts', -1) #7 pipeline.execute()
release_lock(conn, key, lock) return True
#1 Acquire a lock around the status object to ensure that no one else is trying to delete it when we are.
#2 If we didn't get the lock, return.
#3 If the user doesn't match the user stored in the status message, return.
#4 Delete the status message.
#5 Remove the status message ID from the user's profile timeline.
#6 Remove the status message ID from the user's home timeline.
#7 Reduce the number of posted messages in the user information HASH.
While deleting the status message and updating the status count, we also went ahead and removed the message from the user's home timeline and profile timeline. Though this isn't technically necessary, it does allow us to keep both of those timelines a little cleaner without much effort.
Exercise: Cleaning out deleted IDs
As status messages are deleted, "zombie" status message IDs will still be in the home timelines of all followers. Can you clean out these status IDs? Hint: Think about how we sent the messages out in the first place. Bonus points: also handle lists.
Being able to post or delete status messages more or less completes the primary functionality of a Twitter-like social network from a typical user's perspective. But to complete the experience, you may want to consider adding a few other features:
- Private users, along with the ability to request to follow someone
- Favorites (keeping in mind the privacy of a tweet)
- Direct messaging between users
- Replying to messages resulting in conversation flow
- Reposting/retweeting of messages
- The ability to @mention users or #tag ideas
- Keeping a record of who @mentions someone
- Spam and abuse reporting and controls
These additional features would help to round out the functionality of a site like Twitter, but may not be necessary in every situation. Expanding beyond those features that Twitter provides, some social networks have chosen to offer additional functionality that you may want to consider:
- Liking/+1 voting status messages
- Moving status messages around the timeline depending on "importance"
- Direct messaging between a prespecified group of people
- Groups where users can post to and/or follow a group timeline (public groups, private groups, or even announcement-style groups)
Summary
In this article, we showed you post or delete a status update on Twitter. If you dig into chapter 8 of Redis in Action, you'll see that we've built the majority of functionality that makes a site like Twitter work. Though these structures won't scale to the extent that Twitter does, the methods used can be used to build a small social network easily. With a front end for users to interact with, you can start your own social network with your friends!
If there's one thing that you should take away from this chapter, it's that even immensely popular websites have functionality that can be built with the tools available inside of Redis.
Here are some other Manning titles you might be interested in:
Java and the Internet, a perfect match
When we started building our first Java application, at my company Amway Corp, many years ago;
we learned our first lesson.
In spite of all the formal training we received, in spite of all the literature at our disposal;
we still needed help with our Java development on a regular basis.
Where would this assistance come from?
At the time, we had no in-house Java subject-matter experts.
What we wanted was to have access to Java "wisdom" from other java developers.
We wanted to be able to see how others would do things in Java.
Fortunately, we had a tool which would provide a means in which to achieve this...
The Internet.
Searching the internet, via web browser search engine became a valuable tool
for answering our most detailed questions about Java development.
We quickly discovered the vast amount of information available through the internet
about Java development. We found resources about Java concepts, design, and sample solutions.
We felt as if we had made a great discovery.
Foremost on these internet-based resources was the Java forum web-site operated by
Sun Microsystems, a previous caretaker of Java.
Code fragments posted by other developers, on this site, gave us answers to our questions.
The forums included a text search capability so we could search by word or by phrase.
We could use a Java-specific word such as "java.io" or a phrase such as "storing images".
Time and time again, we would go to the internet and specifically Sun's Java forum web-site
to get specific answers to our questions.
Time and time again we would get our answers in the form of actual code fragments
that we could immediately put to use.
This information was free to use, freely given to whomever wanted it,
and provided a means give feedback to the contributor of the Java information.
There seemed to be no Java question that we could not find an answer to.
We were simply amazed with how easy it was to "connect" with other Java developers.
Sometimes we felt like standing up from our desks and shouting, "Thank you, Internet!!!"
As our Java expertise grew, we relied less and less and the internet for answers.
When we look back and salute all the contributors to our Java successes over the years,
we have to include the internet and the many givers of Java wisdom who have freely
given so that others may receive.
Meet the author behind 'MVC applies to JavaScript' - Sebastiano Armeli-Battana
Sebastiano Armeli-Battana is the author of the successful 'MVC Applies to JavaScript' eBook.
We thought we'd get to know a little more about the author!
1. For someone that’s new to the JavaScript sector, can you explain why they should use MVC?
I would say that a JS noob should use MVC, just because it’s widely spread pattern used across different programming languages. I think they would enjoy it the most.
2. How did you start working with UI development?
To begin with I started working on translating PSDs into web pages. After a while I enjoyed the fact that I could see the results of what I was developing almost immediately. It was (and still is) really satisfying. That’s probably the best thing in UI development in my opinion.
3. What would be your main piece of advice for someone who wanted to get started with backbone.js?
Definitely the first step would be to become familiar with all the Backbone components. Look at how the model and the view are bound together! It’s really interesting!
4. Is your book aimed at beginners, intermediate or senior developers?
I guess it is more for intermediate developers, but it could be a good read for a senior developer who wanted to brush up on his or her knowledge.
5. What was the most challenging aspect of writing MVC Applies to JavaScript?
Working full time and writing the ePub at the same time! Other than that, it was an enjoyable experience.
6. How did you first get into developing/coding?
I love problem solving and developing is all about that, right?
7. What individuals or companies do you admire most/heroes in the tech space?
Well, I admire many companies their innovations. I will mention a few of them: Facebook, Twitter, Github, Google, Cloudfare, SauceLabs, etc. There is a long list of smart and passionate people I admire as well, too many to list really.. Paul Irish, Stoyan Stefanov, Nicholas Zakas, Jeremy Ashkenas to mention a few..
8. What sort of music do you like?
Big fan of electronic!
Want to find out more about Sebastiano’s ebook? Head on over to our website where it is available to buy now for only $3.99!
http://developerpress.com/en/mvc-javascript
Why I Love WebSockets
When I was in school, passing notes took some effort.
First, you needed to find a piece of paper that was large enough for your message, but small enough that it could be folded into the requisite football shape. Next, you had to write something. Anything smaller than several sentences just wasn’t worth the overhead, so you had to write about half a page’s worth of stuff, or draw a picture large and detailed enough to make it worth it. After that, you set about the process of folding your note into the aforementioned form. Finally, you had to negotiate with your neighbor to get the note from your desk to its final destination. All that was just to send the message. On the receiving side, the note was unfolded and read. Then your counterpart would go about constructing a response, refolding the note, and negotiating the return trip.
Passing notes in class was a task that required effort, skill and time. You sent a message and you waited for a response. If you thought of something new that you really needed to say, you had to wait until the response came back. At that point, you could alter your original message or add new content. While your note was in transit or being read and replied to on the other end, you had no control. You were at the mercy of the medium over which you were forced to communicate. Note passing simply isn’t designed to allow for short, quick, asynchronous communication.
Nowadays, kids just text each other on their smartphones. They send messages quickly and easily without having to invest in all that overhead. After a bit of upfront work to get someone’s phone number, the back channel classroom chatter flows freely. That is, until someone forgets to silence their phone and the teacher confiscates everything with a battery.
Just as the methods of slacking off in school have evolved, so have methods of communicating over the Web. HTTP is the note passing of the Internet. It works well enough for most communications, and when the message is large enough, the overhead is minimal. However, it is less efficient for smaller messages. The headers included by browsers these days can easily outweigh the message body.
Also, just like note passing, HTTP is synchronous. The client sends a request and waits until the server responds. If there is something new to be said, a new request is initiated. If the server has something to add, it has to wait until it is asked. It can’t simply send a message when it is ready.
WebSockets are the smartphone to HTTP’s notes. They let you send information quickly and easily. Why go through all that folding when you can simply send a text to say “idk, wut do u think we should do?” Why use 1K of headers when all you want to know is, “Did someone else kill my rat?” Better yet, why ask at all? Why not have the server tell you when the rat has been killed by someone else?
WebSockets are made for small messages. They are made for asynchronous communications. They are made for the types of applications users expect these days. That’s why I like WebSockets so much. They let me communicate without overhead or rigorous process. I can write an application that is free from request/response pairs. I can write an application that responds as quickly as my users can act. I can write the applications that I like to write.
About the Author
Scott Mattocks is the Director of Development at GSN Digital. He leads a team of highly skilled developers, driving growth and scale of GSN’s on-line games platforms. Scott lives in Massachusetts with his wife and four kids.
Scott has written an ebook with Developer.Press on WebSockets.
'WebSockets - An introduction to real-time communications for the Web' is available now to buy: http://developerpress.com/en/websockets-introduction
New enhancements to Admin Command framework in Glassfish 4.0
 Glassfish 4.0 is released. This is the reference implementation for Java EE 7 and focusses on HTML 5 and improving developer productivity. You can download the bits from here https://glassfish.java.net/download.html
Apart from the Java EE 7 support in GlassFish 4.0 there have been numerous other areas where Glassfish 4 has provided lots of improvements and innovation
Martin Mares , Chris Kasso and I have been working on the Admin Command Framework.
These are some new enhancements that were added to Glassfish 4.0.
o Support for Progress status using Server Sent Events
o Job Management support
This section will cover the newly introduced @Progress annotation. We will walk through the basic usages of Progress API.
Next we will see how ServerSentEvents fits in with the Progress API.
Consider some long running commands say start-cluster. It would be useful to be notified about the progress of the command as it is executing.
To facilitate support for Progress status in AdminCommands a new annotation @Progress is added.
Any command which wants to use the Progress status API can be annotated with @Progress
The ProgressStatus object can be obtained from the AdminCommandContext.
The Progress API can be used to specify the total steps for execution. Once the total steps are known the percentage can be computed.
Additionally the ProgressStatus API takes a message that can be added as the command progresses like Installing, Parsing... etc.
As the command is executing, the progress can be updated by specifying the steps and the message to be sent to the client.
@Progress public class SomeCommand implements AdminCommand { public void execute(AdminCommandContext context) {
ProgressStatus ps = context.getProgressStatus(); ps.setTotalStepCount(3); ... .. ps.progress(1, "Parsing files..");
The above snippet shows the @Progress annotation on the command. It also demonstrates how to get the ProgressStatus object from the AdminCommandContext.
It shows how to use the ProgressStatus.progress() method to specify the number of steps taken and a message to be emitted.
Here is the Progress Status API which command developers can read for detailed information. http://grepcode.com/file/maven.java.net/content/groups/promoted/org.glas...
Server-Sent Events (SSE) is a technology for providing push notifications from servers to clients once an initial client connection has been established.
For our case of long running commands which emits progress as it executes, the server can continuously sending the progress using Server Sent Events API.
Any command which has progress information in it ie annotated with @Progress or which is run with --detach (See section below) option is known as a ManagedJob. Each job has a job id associated with it.
You can query the status of a ManagedJob using list-jobs command.
1. When a managed job is executed in GlassFish the REST client will open an SSE connection with header Accept: text/event-stream.
2. The command gets executed on a dedicated thread pool which is provided by the JobManager.
3. Once the channel of communication is established all the progress feedback is sent as Server Sent Events and the channel is kept open to keep sending progress as it occurs.
4. The Response is closed when the command finishes execution.

The above figure shows the interaction between the Server and the command which is annotated with @Progress executed by the client.
The progress is sent via SSE and finally the ActionReport is sent once the command finishes execution.
These are newer commands which are introduced
- detach option to commands
- attach command
- list-jobs command
- configure-managed-jobs
Any command can be run with --detach option. This will give a job id associated with the command and the job is run in the background.
You can then lookup the job using the list-jobs command. (Similar to the jobs command in Unix)
You can later attach to the job using the attach command with the job id too and see the progress.
The following image shows a sample command started by the client which emits progress status information.
1. Client 1 starts the sample command which has some progress information
2. The server executes the command and sends the progress to the client using ServerSentEvents.
You can open another terminal for Client 2 and
attach to the same job and see the same progress updates on both the clients.

Fig 1. Multiple clients attaching to get progress via Server Sent Events.
Bboth the terminals Client1 and Client2 are both getting the same set of progress related Server Sent Events at the same time. Even if one client kills using Ctrl C the other will still see the updates.
The list-jobs command can provide information regarding the jobs.
It lists the job id, the name, the time the job was started, the state and the Exitcode.
Here is a sample output of list-jobs command
asadmin list-jobs NAME JOB ID TIME STATE EXIT CODE USER sample-command1 1 2013-02-05 14:11:24 COMPLETED SUCCESS admin
You can even run list-jobs with a single job id
asadmin list-jobs 1 NAME JOB ID TIME STATE EXIT CODE USER sample-command1 1 2013-02-05 14:11:24 COMPLETED SUCCESS admin
Using curl to get the data of the list-jobs
This will get the information of all jobs curl -vSs -H 'X-Requested-By foo' -X GET http://localhost:4848/management/jobs
This will get the information of job whose id is 1 curl -vSs -H 'X-Requested-By foo' -X GET http://localhost:4848/management/jobs/id/1
The configure-managed-jobs command is used to clean up these ManagedJobs. By default the job retention period is 24 hours. But using this command you can specify how long you want to keep the jobs.
Download GlassFish 4.0 from https://glassfish.java.net/download.html and try the newer features.
Java EE 7 tutorial is here http://docs.oracle.com/javaee/7/tutorial/doc/home.htm
You can file bugs using this link https://java.net/jira/browse/GLASSFISH
Provide feedback at users@glassfish.dev.java.net.
Using Throws and Throw Statements in Java

Using Throws and Throw Statements in Java
By Mala Gupta, author of OCP Java SE 7 Programmer II Certification Guide
In this article, based on chapter 1 of OCP Java SE 7 Programmer II Certification Guide, author Mala Gupta explains how to define methods that throw exceptions, the different combinations of defining overriding methods, and when the overridden or overriding methods throw checked exceptions. Save 42% on OCP Java SE 7 Programmer II Certification Guide with Promotional Code ocplaujn, only at manning.com.
Imagine you have been assigned a task of finding a specific book, and then reading and explaining its contents to a class of students. The required sequence may look like:
- Get the specified book
- Read aloud its contents
- Explain the contents to a class of students.
But what happens if you can't find the specified book? You can't proceed with the rest of the action without it so you need to report back to the person who assigned the task to you. This unexpected event (missing book) prevents you from completing your task. By reporting it back, you want the originator of this request to take corrective or alternate steps.
Let's code the above task as method teachClass, as shown in figure 1 and use it to compare the throw and throws statement. This example code is for demonstration purpose only because it uses methods locateBook, readBook, and explainContents, which aren't defined.
Figure 1 Comparing throws and throw statement
Code in figure 1 is simple to follow. On execution of code throw new BookNotFoundException, execution of teachClass() halts. The JVM creates an instance of BookNotFoundException and sends it to off to the caller of teachClass() so that alternate arrangements can be made.
The throw statement is used to throw an instance of exception—BookNotFoundException. The throws statement is used in the signature of method teachClass to signal that it can throw exception BookNotFoundException.
Why does a method choose to throw an exception as opposed to handling it itself? It's a contract between the calling method and the called method. Referring back to the method teachClass, as shown in figure 1, the caller of teachClass would like to be informed if teachClass is unable to find the specified book. The method teachClass doesn't handle BookNotFoundException itself because its responsibilities don't include how to work around a missing book.
Creating a method that throws a checked exception
Let's create a simple method, which doesn't handle the checked exception thrown by it, by using the keywords throw and throws. Class DemoThrowsException defines method readFile, which includes a throws statement in its method signature. The actual throwing of an exception is accomplished by the throw statement:
import java.io.FileNotFoundException; class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { #A boolean found = findFile(file); if (!found) throw new FileNotFoundException("Missing file"); #B else { //code to read file } } boolean findFile(String file) { //code to return true if file can be located } }
#A The throws statement indicates that this method can throw FileNotFoundException
#B If file can't be found, code creates and throws an object of FileNotFoundException by using the throw statement
A method can include names of multiple, comma separated names in its throws statement. It isn't obligatory to include names of Runtime exceptions or errors in the throws statement. A method can still throw instances of Runtime exceptions or errors, without including them in its throws statement.
Using a method that throws a checked exception
When you use a method that throws a checked exception, you can:
- Enclose the code within a
try block and catch the thrown exception.
- Declare the exception to be rethrown in the method's signature.
- Implement both the above together.
In the following example, method useReadFile encloses the usage of the method readFile within a try-catch block. Method readFile throws FileNotFoundException (a checked exception):
class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { //..code } void useReadFile (String name) { #A try { #B readFile(name); #B } #B catch (FileNotFoundException e) { //code } } }
#A Method useReadFile uses method readFile that throws FileNotFileException
#B Call to method readFile should be enclosed in a try block because it throws checked exception FileNotFoundException
In the modified definition of method useReadFile, you can make the method useReadFile throw the exception thrown by the method readFile:
class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { //..code } void useReadFile(String name) throws FileNotFoundException{ #A readFile(name); #B } }
#A useReadFile() declares that it throws exception FileNotFoundException
#B Usage of method readFile need not be enclosed in a try block
The compiler doesn't complain if you mix the above approaches—method useReadFile can handle FileNotFoundException itself and still declare it to be thrown (highlighted using boldface):
import java.io.*; class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { //..code } void useReadFile (String name) throws FileNotFoundException{ #A
try { #B readFile(name); #B } #B catch (FileNotFoundException e) { //code } } }
#A useReadFile() declares that it throws exception FileNotFoundException
#B Usage of method readFile is enclosed in a try block
So what happens when FileNotFoundException is thrown by method readFile()? Will its catch block handle FileNotFoundException, or will it throw it to its calling method?
Points to note while using throws and throw statement
Apart from knowing the need of throwing exceptions, using their syntax, you should be aware about a couple of rules to throw exceptions using throw and throws statement, as discussed in this section.
It isn't obligatory to include runtime exceptions or errors in throws statement
Let's modify the above example so that method readFile throws a runtime exception—NullPointerException, when a null value is passed to it (changes in boldface):
import java.io.FileNotFoundException; class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { #A if (file == null) throw new NullPointerException(); #B boolean found = findFile(file); if (!found) throw new FileNotFoundException("Missing file"); #C else { //code to read file } } boolean findFile(String file) { //code to return true if file can be located } }
#A The throws statement indicates that this method can throw FileNotFoundException
#B Code throws NullPointerException, but it is not included in throws statement
#C If file can't be found, code creates and throws an object of FileNotFoundException
The exam might trick you by including the names of runtime exceptions and errors in one method and leaving out in another. You can include the name of a runtime exception in the throws statement. Assuming that the rest of the code remains the same, the following method signature is correct:
public void readFile(String file) throws NullPointerException, FileNotFoundException { #A //rest of the code remains same }
#A Though not required, inclusion of runtime exceptions in the throws statement is valid
EXAM TIP It isn't obligatory to include the name of the runtime exceptions or errors in the throws statement. A method can throw a runtime exception or error irrespective of whether their names are included in method's throws statement.
A method can throw a subclass of exception mentioned in its throws statement not its superclass
Because class IOException is a superclass of class FileNotFoundException, method readFile, can't throw an object of class IOException:
class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { #A boolean found = findFile(file); if (!found) throw new IOException("Missing file"); #B else { //code to read file } } boolean findFile(String file) { //code to return true if file can be located } }
#A The throws statement includes FileNotFoundException
#B Won't compile—can't throw an object of superclass of checked exception mentioned in throws statement
Let's modify the definition of method readFile by making it throw IOException. Because IOException is a super class of class FileNotFoundException, readFile() can throw an object of FileNotFoundException (changes in boldface):
class DemoThrowsException { public void readFile(String file) throws IOException { #A boolean found = findFile(file); if (!found) throw new FileNotFoundException("Missing file"); #B else { //code to read file } } boolean findFile(String file) { //code to return true if file can be located } }
#A The throws statement includes IOException
#B Will compile—can throw an object of derived class of checked exception mentioned in throws statement
Note that this rule doesn't apply to the errors and runtime exceptions because the throws statement doesn't need to specify the names of the errors and runtime exceptions.
A method can handle the exception and still declare it to be thrown
This is usually done by methods whose exception handlers might throw the same exception. The method useReadFile() handles the exception FileNotFoundException and also declares it to be rethrown:
class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { //..code } void useReadFile(String name) throws FileNotFoundException { #A try { readFile(name); } catch (FileNotFoundException e) { #B //code
throw new FileNotFoundException(); #C } } }
#A useReadFile() throws FileNotFoundException
#B This code is valid—useReadFile() handles FileNotFoundException from method readFile
#C This exception instance will be handed over to method that calls method useReadFile
A method that declares a checked exception to be thrown might not actually throw it
Method readFile() includes the name of checked exception—FileNotFoundException—in its throws statement, but doesn't throw it:
import java.io.FileNotFoundException; class DemoThrowsException { public void readFile(String file) throws FileNotFoundException { #A System.out.println("readFile:" + file); #A } #A }
#A Compiles successfully even if readFile doesn't throw an instance of FileNotFoundExcception
But do you think you can call readFile() as a method that doesn't throw an exception, that is, without enclosing it within a try-catch block or rethrowing the exception?
Rethrowing exceptions with more inclusive type checking
Starting with Java version 7, the type of the variable that you use to rethrow a thrown exception can be more generic in the catch block:
class GenericVariableTypeToRethrowException { public static void main(String args[]) throws IOException, SQLException { #A String source = "DBMS"; try { if (source.equals("DBMS")) throw new SQLException(); else throw new IOException(); } catch (Exception e) { #B throw e; #C } } }
#A Method declares to throw exceptions IOException and SQLException
#B Type of variable e in catch block is Exception—more generic than IOException and SQLException
#C Catch block rethrows the caught exception
In the try block, the code throws either an object of SQLException or IOException, conditionally. With Java 7, the compiler can determine that the exception object received by the catch block is either of these types and so it's okay to rethrow it, even if the type of the exception variable in the exception handler is Exception—a super class of SQLException and IOException. This, however, wasn't allowed in Java versions prior to 7.
Do you think the code will compile successfully if instead of rethrowing the exception in the catch block, you create a new object of class Exception and throw it? No, it won't. Because it would be a direct violation of the contract between the declaration of exceptions that method main states to be throwing and what it actually throws.
EXAM TIP With Java 7, you can rethrow exceptions with more inclusive type checking.
Summary
Exception handling is covered both in the OCA Java SE 7 Programmer I exam (1Z0-803) and OCP Java SE 7 Programmer II exam (1Z0-804). In this article, I covered a topics that are specific to the latter exam: the throw and throws statements.
You can throw your own custom exceptions from methods by using the throw and throws statement, in the same way you work with the exception classes from the Java API.
Here are some other Manning titles you might be interested in:
BDD with JavaScript
Test Driven Development (TDD) has become a cornerstone of modern software craftsmanship. Behaviour Driven Development (BDD) takes it to the next level; it provides easier to use and a more readable syntax as well as many other improvements. If you haven't used Test Driven Development before, start with BDD, you will reap the benefits much faster.
This book is a hands-on introduction on BDD. Using Jasmine, a BDD framework for JavaScript, you will learn step-by-step how to write maintainable specifications. You will see how to embed BDD in your daily coding and learn its do's and don'ts.
When reading this book you will:
•Apply modern JavaScript techniques such as function expressions and ECMA5-object handling.
•Learn the mechanics and the process of BDD.
•Write specs with the popular Jasmine framework.
•Use specs as living documentation.
•Create data with Example Factories.
•Organize your specs in various ways, depending on the situation.
•Use expectations and code custom matchers.
•Drive new features from the outside in.
•Isolate your specs with mock objects and methods.
Example project
Meet Anna, Chris and Steve who are part of a fictional team that demonstrate BDD techniques step by step on a fictional project. You will get an idea of what it means to apply BDD in to a real industrial environment.
Exercises and katas.
As well as the theoretical foundation and practical examples, this book provides you with exercises and katas. Try out newly learnt techniques with real code and you’ll never forget them!
What is BDD?
Since BDD is often debated, there is one chapter dedicated to all of the questions and debates which regular arise. This book also delves in to the actual meaning of BDD and it highlights some surprising results which will possibly challenge you current point of view.
Interested in reading more? You can get your hands on the ebook now from the Developer.Press website: http://developerpress.com/en/behaviour-driven-development-javascript-1 for only $3.99! Bargain!
All brand names,logos and trademarks in this site are property of their respective owners.
|