In previous parts of this post, we figured out how to create a new webserivce implemented in JAX-WS using java language, and the create a RIA application using Silverlight to use this service. Let’s continue and see some real-world scenarios.

Continuing from the last part, let’s add a new functionality to our service to save a new blog post.

1
2
3
4
5
6
7
8
9
public PostDto createNewPost(PostDto postDto){
PostMapper mapper = new PostMapper();
Post post = mapper.InverseMapOne(postDto);

em.persist(post);
PostDto result = mapper.MapOne(post);

return result;
}

Nothing fancy here, but let’s validate the postDto sent by the client and make sure it is valid before saving it. Our business rule says that a post should have a blog associated with, so make sure it does that and throw an exception if this rule is not valid. Our “createNewPost” changes into this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public PostDto createNewPost(PostDto postDto) throws BlogServiceException {
if(postDto == null)
throw new BlogServiceException("No PostDto was submitted to the service.");
if(postDto.getTitle() == null)
throw new BlogServiceException("Post title was not specified");

if(postDto.getBlog() == null)
throw new BlogServiceException("Owner blog was not specified on the post.");

PostMapper mapper = new PostMapper();
Post post = mapper.InverseMapOne(postDto);

em.persist(post);
PostDto result = mapper.MapOne(post);

return result;
}

Java languages has checked exception rules, so when the method here throws an exception, we should also add the “throws” syntax to the service interface.

To send the client the validation messages, we’ve created an exception class that accepts a message. Just like .NET exceptions, all java exceptions derive from Exception class. But wait a second…Didn’t WebService standards imply that we should use SOAP Faults, instead of native exceptions? Exceptions are platform dependent, after all, and should be avoided when exposing a service through the web. The answer is, yes, but “unmodeled faults” are still converted to fault objects on the fly, so no worries, as the client will get the exception object as a fault.

Now, let’s update our client and call the newly created service and see what happens when we pass the wrong data.