Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted March 21st, 2016
Asynchronous web application with Atmosphere

Defining Atmosphere will depend with your occupation but whether you are a scientists or a programmer the meaning is related. The most suitable definition is a distinctive but intangible quality surrounding a person or thing.
In Java the Atmosphere framework works with every Java EE Application Server and automatically negotiates the best transport between the client and server. Atmosphere’s support portable Web Sockets with Jetty, Glass Fish, Grizzly 2, Tomcat and Netty.
If your planning to develop an asynchronous universal application that can be deployed anywhere atmosphere is the way to go.

There are three basic operations that an Asynchronous web application require.

  1. Suspend-The action of suspending holds the response before it is sent to the server.
/*
*
 * Suspend the response without writing anything back to the client.
 *
 * @return a white space
 */
@Suspend(contentType = "application/json", listeners = {AtmosphereResourceEventListenerAdapter.OnDisconnect.class})
@GET
public String suspend() {
    return "";
}
  1. Resume -It’s the state of completing the response. The count represent the number of Broadcast event that need to happen before the suspended response gets resumed.

  2. Broadcast- Generating an event from the server and distributing that event to suspended response. Suspended response then decide either to discard the event or send it back to the browser.

To get started and build a chat application follow the following steps.

Copy the following command to your terminal.

mvn archetype:generate -DgroupId=com.chat -DartifactId=Tony_Chat_App -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Add the following in the pom.xml and define the atmosphere‐runtime and it’s dependencies

    <dependency>
    <groupid>org.atmosphere</groupid>
    <artifactid>atmosphere-runtime</artifactid>
    <version>2.4.2</version>
    </dependency>

Create a java class and paste this code.

    package tk.gregsource.app;

    import org.atmosphere.cpr.AtmosphereRequest;
    import org.atmosphere.cpr.AtmosphereResource;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;

    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Date;
    @Controller
    public class AtmosphereController {
    ArrayList<httpsession> subscribers = new ArrayList</httpsession><httpsession>();

    @RequestMapping(value="/", method = RequestMethod.GET)
    public ModelAndView getView() { return new ModelAndView("chat");
    }

    @RequestMapping(value = "/chat", method = RequestMethod.GET)
   @ResponseBody public void onRequest(AtmosphereResource atmosphereResource, HttpSession session)
        throws IOException{
        AtmosphereRequest atmosphereRequest = atmosphereResource.getRequest();
        System.out.println(atmosphereRequest.getHeader("negotiating"));
        if(atmosphereRequest.getHeader("negotiating") == null) {
            atmosphereResource.resumeOnBroadcast(atmosphereResource.transport() == AtmosphereResource.TRANSPORT.LONG_POLLING).suspend();
        } else {
            atmosphereResource.getResponse().getWriter().write("OK");
        }

        subscribers.add(session);

        System.out.println("Subscribers: " + subscribers.size());

        for(HttpSession httpSession : subscribers) {
            System.out.println(httpSession);
        }

    }

    @RequestMapping(value = "/chat", method = RequestMethod.POST)
    @ResponseBody
    public void onPost(AtmosphereResource atmosphereResource) throws IOException{

        AtmosphereRequest atmosphereRequest = atmosphereResource.getRequest();

        String body = atmosphereRequest.getReader().readLine().trim();

        String author = body.substring(body.indexOf(":") + 2, body.indexOf(",") - 1);
        String message = body.substring(body.lastIndexOf(":") + 2, body.length() - 2);

        atmosphereResource.getBroadcaster().broadcast(new Data(author, message).toString());

    }

    private final static class Data {

        private final String text;
        private final String author;

        public Data(String author, String text) {
            this.author = author;
            this.text = text;
        }

        public String toString() {
            return "{ \"text\" : \"" + text + "\", \"author\" : \"" + author + "\" , \"time\" : " + new Date().getTime() + "}";
        }

    }
}

Create a java class and paste this code.

    package tk.gregsource.app;
    import org.atmosphere.cpr.AtmosphereResource;
    import org.atmosphere.cpr.Meteor;
    import org.springframework.core.MethodParameter;
    import org.springframework.web.bind.support.WebDataBinderFactory;
    import org.springframework.web.context.request.NativeWebRequest;
    import org.springframework.web.method.support.HandlerMethodArgumentRes    olver;
    import org.springframework.web.method.support.ModelAndViewContainer;

    import javax.servlet.http.HttpServletRequest;



public class AtmosphereResolver implements HandlerMethodArgumentResolver{

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return AtmosphereResource.class.isAssignableFrom(methodParameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Meteor m = Meteor.build(nativeWebRequest.getNativeRequest(HttpServletRequest.class));
        return m.getAtmosphereResource();
    }
}

NB I used spring framework to simplify the app.

Posted by Tonny Mwirigi

Leave a Reply

Your email address will not be published. Required fields are marked *