Thursday, June 25, 2015

WebAssembly, an end of Javascript?

No comments:
Apple, Google, Microsoft and Mozilla have joined together for a common cause!

Are you kidding me?

All these companies are rivals, then how come is this possible?

Yeah it is true. They all joined together and developing a new web programming standard called "WebAssembly".

What is WebAssembly?

WebAssembly is a universal binary and text format for the web. In short form this is being called as 'wasm' WebAssembly in a binary format which is a low-level binary format than Javascript.

Why does it matter?

WebAssembly's binary data is smaller in size. Which means the binary data will be downloaded quickly. Since it is in a binary format, the decoding and execution is also much faster than Javascript.

This is already proved by Mozilla engineers. They recently released some preliminary performance numbers for WebAssembly. Based on their data, wasm is 20-30% smaller in size and 23x times faster than parsing. Which is pretty good performance numbers even at the earliest stage of the wasm development.

The name "WebAssembly" got traction recently because all the 4 big companies in the browser market have one voice. So there is no doubt on the adoption of the technology. 

WebAssembly is a binary format which will be standardized soon. Once it is standardized we can write code in any programming language and the compilation will generate the binary format which is understandable by the wasm standards. They are targeting C/C++ languages for their initial version. All the other programming languages will be supported going forward.

They have already hosted a project in GitHub and working on the design for wasm. You can also join the w3 community and participate in the discussion.

Other initiatives:

Over the last few years Google, Apple and Mozilla are working on the same domain with different goals. Google is already working on PNaCl (portable Native Client). Apple is working on FLT LLV and Mozilla is working on asm.js. Unfortunately Microsoft has any no counter part so far.

All these companies have different learning from the above initiatives. Since they all joined together, all their learning will be applied into WebAssembly programming. So we can be believe that, WebAssembly will make a great impact with the current web programming domain.

Is that an end of Javascript?

As you all know Javascript is the dominant programming language for the web. Javascript eco system is so big and lot of enhancements are also planned for the next ES6 upgrades. Since wasm is being under the development now, it will take some time to find the user base.

But definitely wasm will take a big share from Javascript. Some of the use-cases are image processing and memory consuming operation in browser. wasm team announced that, we can even develop a full fledged web application with wasm. Since this can be possible using our known programming languages, there will be no need to learn Javascript anymore :(

But wasm community is claiming that, instead of a threat, wasm will enhance Javascript. What ever it may be, this would be a great time for all of us as a web programmer and an user. We are going to get lot of fun stuff on the web very soon...

Please share it with your friends and subscribe the newsletter if you like the article. Keep watching this space for more updates...

Read More

Tuesday, May 19, 2015

How to embed Gist source code into Blogger?

No comments:
I hope you all know about "Gist" If you don't know the definition already, here you go...

"Gist is a simple way of sharing source code snippets or samples with others" - Taken from definition.

Today we are going to see how easy to embed Gist code with our blogs. You would have faced such a pain, when you write some technical article with lots of source code references(Could be any language :() Formatting the source code will take much longer time, than your whole content of an article.

Here I am going to explain, how easy it is to embed the external source code into our blog posting without much effort. Looks simple...

Yes it is. Here you go...

<div class="gistLoad" data-id="GIST_ID" id="gist-GIST_ID"></div>
<script src="https://gist.github.com/zarub2k/GIST_ID.js"></script>
<script src='https://raw.github.com/moski/gist-Blogger/master/public/gistLoader.js' type='text/javascript'></script>

GIST_ID: This is the actual Gist id which can be taken after you create any Gist. This has to be replaced with the original id.

The actual Gist source code is being referred by the second line. This line has to be replaced with the original Gist source link.

Finally this is how the source code will be rendered in your blog post. Enjoy sharing lot of source codes :)

Share the post and give your feedback and comments if any...

Read More

Monday, May 18, 2015

Better exception handling in RESTful Java

1 comment:
"Less time on exception handling at development, hard time on debugging in production"

Whenever we start learning a new programming language or concepts, it is better to understand how to handle the extreme cases or exceptions.

In this article, we are going to see how we can handle exceptions when we write RESTful web services using Java language. There are 3 main parts involved in the process.


  • Exception wrapper
  • Exception mapper
  • Response marshaller
We will see each one of them in details...

Exception wrapper:

First we have to write a exception wrapper of our business exception. Something like an extended implementation of Java exception. This is an exception which we will throw from our business logic. 

public class CustomException extends Exception implements Serializable {

  private static final long serialVersionUID = -2018114370574835493L;
  public CustomException() {
    super();
  }

  public CustomException(String message) {
    super(message);
  }

  public CustomException(String message, Exception ex) {
    super(message, ex);
  }
}

Exception mapper:

Next we have to write a provider class for the above mentioned custom exception. This one is called as exception mapper. It will generate the desired response from our custom exception object at run-time.


@Provider
public class CustomExceptionMapper implements ExceptionMapper<CustomException> {

@Override
public Response toResponse(CustomException ex) {
CustomResponse CustomResponse = new CustomResponse(Response.Status.EXPECTATION_FAILED.getStatusCode());
CustomResponse.setMessage(ex.getMessage());

StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
CustomResponse.setDetail(writer.toString());

return Response.status(Response.Status.OK.getStatusCode())
.entity(CustomResponse)
.type(MediaType.APPLICATION_JSON)
.build();
}
}

Response marshaller:

Marshaling is the process of creating JSON / XML data from the given object. In our case we are going to create JSON response from the given Custom Response object. Custom Response object is the holder for the response which will be transferred as a JSON data. Marshalling Java to JSON is covered in details. Please refer if you need more information 


@Provider
@Produces(MediaType.APPLICATION_JSON)
public class CustomResponseMarshaller implements MessageBodyWriter<CustomResponse> {

@Override
public long getSize(CustomResponse CustomResponse, Class<?> clazz,
Type type, Annotation[] annotations, MediaType mediaType) {
return -1;
}

@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return clazz == CustomResponse.class;
}

@Override
public void writeTo(CustomResponse CustomResponse, Class<?> clazz,
Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> valueMap, OutputStream stream) throws IOException, WebApplicationException {

JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("status", CustomResponse.getStatus());

jsonObjectBuilder.add("data", (CustomResponse.getData() != null) ? CustomResponse.getData() : "");
jsonObjectBuilder.add("message", (CustomResponse.getMessage() != null) ? CustomResponse.getMessage() : "");
jsonObjectBuilder.add("detail", (CustomResponse.getDetail() != null) ? CustomResponse.getDetail() : "");

DataOutputStream outputStream = new DataOutputStream(stream);
outputStream.writeBytes(jsonObjectBuilder.build().toString());
}
}

Finally we can throw our custom exception from the resource method like the below. The Custom exception will be handled based on the provider (mapper) available above in the code.

@Path("hello")
public class CustomRequestResource {

@POST
@Produces(MediaType.APPLICATION_JSON)
public Response request(@FormParam("name") String name,
@FormParam("email") String email,
@FormParam("message") String message) throws CustomException {

if (name == null || email == null || message == null) {
      throw new CustomException("Please fill name, email and message");
    }
 
return Response.status(CustomResponse.getStatus())
.entity(CustomResponse)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
I hope you have enjoyed with this article. Share your comments and feedback if you have any...

Read More

Saturday, December 20, 2014

Marshalling Java to JSON in JAX-RS

1 comment:
In this article, I am going to explain about the purpose and the process of writing custom marshaller for web services. First we have to be clear on what is marshaller. Marshalling is the nothing but the process of converting in-memory object into persisting or transportable format.

Now a days most of the web services are returning the response as JSON object. Some people are still using XML as their preferred transport medium.

JAX-RS api has introduced a generic and pluggable interface called MessageBodyWriter for doing the marshalling.

Use-case:

We will take an use-case in-order to understand the situation little better. We have a Java bean called Book. Now we have to write a REST service which will fetch the Java object from the given ID and return JSON response back to the client.

Book.java:

public class Book {
private String title;
private String author;

public Book(String title, String author) {
this.title = title;
this.author = author;
}

public String getTitle() {
return title;
}

public String getAuthor() {
return author;
}
}

BookResource.java:

public class BookResource {

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Book getBook(@PathParam("id") String id) {

//DataProvider is simple data holder
DataProvider dataProvider = DataProvider.getInstance();
return dataProvider.getBook(id);
}
}

In the above REST method, we have just returned Java object itself to the client as response. If you notice the @Produces, we are returning the JSON contents back to the client.



Stumbled! The magic happens at the marshalling layer. Now we will see how the marshalling code will look like.

BookJsonMarshaller.java:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class BookJsonMarshaller implements MessageBodyWriter<Book> {

@Override
public long getSize(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return -1;
}

@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return clazz == Book.class;
}

@Override
public void writeTo(Book book, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> valueMap, OutputStream stream) throws IOException, WebApplicationException {

JsonObject jsonObject = Json.createObjectBuilder()
.add("title", book.getTitle())
.add("author", book.getAuthor()).build();

DataOutputStream outputStream = new DataOutputStream(stream);
outputStream.writeBytes(jsonObject.toString());
}
}

We have to look 'writeTo' method just to understand the process. The first arguments is coming from the injection layer so the current Java object will be available to this processor. Now we have process the Java object and should generate JSON object. In this example I have used the 'javax.json.jar' for generating the JSON content. Finally the JSON content should be written into output stream.

Finally we have register the provider (BookJsonMarshaller) into our application like other resources...

Before we conclude this article, you may have one question. Why we need to write the custom marshaller for processing the Java object. Is it not possible by default? You question is valid. This is still possible. But if you want to have a full control over the generated JSON content, we have to write our own @Providers...

I hope you have enjoyed reading this article. If you have any questions or comments please reply to this thread... We will meet again with another discussion.

For code reference, don't forget to visit Github

Advance Christmas wishes to my readers!

Read More

Monday, November 24, 2014

REST service client with JAX-RS API

No comments:

Background:

Are you still using Apache HTTP client or Java URL connection to speak with REST service? Then this article is for you. JAX-RS specification has released with new client API to communicate with RESTful services. Here you can see how you can use JAX-RS client API for your communication.

As a first step, we have to create a web target in-order to talk to our web services. Using the ClientBuilder, we should create a Client object.

From the client object we can create WebTarget object like below,

WebTarget api will accept base path and resource path separately. But we can also give the combined url as a whole to the target method.

Once we get the webTarget object, we are ready to communicate with the REST service. From the webTarget object we can invoke the respective REST methods...

In the above image we have called the get method. This will return the response object. From the response object we can validate the response status and read the entity from the response.

Just to get the JSON string from the response, we have passed the object type (String.class) to the readEntity method. If we get any complex object type, we can still use them.

I hope you will enjoy this article. Please give your comments or feedback if you have any... We will meet shortly with another article.
Read More

Sunday, September 21, 2014

How to write REST client with proxy configurations?

3 comments:

Proxy?

Most of the enterprises have the proxy settings in-order to hide the actual endpoint from the client. Client will interact with the proxy, but the proxy will forward the request to the actual endpoint and return the response back to the client.

So what?

Till now we have seen code, how to communicate directly to the REST end-point. So the approach is straight forward. We don't need to have any special handling for the communication. Where-as if the REST service is hosted behind the proxy how to communicate?

Still thinking how? Don't worry it is very easy with Jersey client API.

client = ClientBuilder.newClient();
client.property(ClientProperties.PROXY_URI, "<proxy_host>:<proxy_port");
After created the client object, we have to add the property with specific with the proxy url configuration into the client.

In some cases, our network proxy has been restricted with user name and password. In such a situation we need to set the user name and password configuration into the client object as below,

client.property(ClientProperties.PROXY_USERNAME, "<username>");
client.property(ClientProperties.PROXY_PASSWORD, "<password>");
This is how we have to communicate with the REST end-point if our services are available behind proxy.

I hope this has clarified your doubts on REST client with proxy configuration. If you have any comments or questions please add your comments below...

Read More

Friday, September 19, 2014

How to write POST method in RESTful Java using Jersey?

7 comments:

Introduction:

In our previous articles, we have seen how to write basic REST services using Jersey framework. And also we saw how to write REST client using Jersey client API. In this article we are going to see, how to write POST method and how to consume the API.

Implementation:

POST method is a special method and it being used interchangeably based on the situation. Meaning some will use POST method for updating an object and some people are using POST method for creating an object. It is up to the user who can decide the situation based on their need.

As you guessed so, the POST method is annotated with @POST annotation. In the below example there are 2 variables are passed from the client.
title
author
Both these parameters are annotated with @FormParam annotation.

@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String createBook(@FormParam(value = "title") String title, @FormParam(value = "author") String author) {
Book book = new Book(title, author);
Gson gson = new Gson(); //Gson is used to simplify the JSON generation process
return gson.toJson(book); //Just send back the JSON to the client. But user can do anything...
}

Client code:

JAX-RS and Jersey have provided lot of useful API's to write REST client code.

//Setting the post method url to the client
WebTarget webTarget = client.target("http://localhost:8080/restfullab/api").path("book");

//Add key-value pair into the form object
Form form = new Form();
form.param("title", "RESTful Java with JAX-RS 2.0 ");
form.param("author", "Bill Burke");

//Send the form object along with the post call
Response response = webTarget.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
System.out.println("Respose code: " +  response.getStatus());
System.out.println("Respose value: " + response.readEntity(String.class));

The parameters will be passed through 'Form' values as key-value pair. 'Key' should match with the @FormParam annotation value.

I hope you have enjoyed reading this post. Please give your valuable feedback or comments if you have any...

We will meet again in few days in another article. Until then enjoy hacking RESTful Java and Jersey framework! 

Source references:

Working source code is available under the following location in Github. Fork and enjoy...
https://github.com/LiquidLab/restfullab/blob/master/src/com/liquidlab/restfullab/resources/BookResource.java
https://github.com/LiquidLab/restfullab/blob/master/test/com/liquidlab/restfullab/resources/test/BookResourceTest.java

Refer Jersey Javadoc for further details...

Read More