Skip to content

Using Kundera with GWT

karthikprasad13 edited this page Mar 25, 2015 · 8 revisions

GWT with Kundera

What is GWT? Google Web Toolkit is an open source set of tools that allows web developers to create and maintain complex JavaScript front-end applications in Java. Other than a few native libraries, everything is Java source that can be built on any supported platform with the included GWT Ant build files. It is licensed under the Apache License version 2.0.[2]

Setting up a GWT project :

  1. Download and Install: Go to http://www.gwtproject.org/download.html and download the GWT Plugin and Web toolkit .

    In order to set up the plugin for eclipse please use the following link: http://www.gwtproject.org/usingeclipse.html

  2. Create a web project using GWT : create project

GWT with Kundera :

  1. Mavenize the project : mavenize

  2. Modify the pom.xml :

<dependencies>
            <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- Kundera Libraries -->
		<dependency>
			<groupId>com.impetus.kundera.core</groupId>
			<artifactId>kundera-core</artifactId>
			<version>2.11</version>
		</dependency>
		<dependency>
			<groupId>com.impetus.kundera.client</groupId>
			<artifactId>kundera-cassandra</artifactId>
			<version>2.11</version>
		</dependency>
		<dependency>
			<groupId>com.impetus.kundera.client</groupId>
			<artifactId>kundera-cassandra</artifactId>
			<version>2.11</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.impetus.kundera.client</groupId>
			<artifactId>kundera-mongo</artifactId>
			<version>2.11</version>
		</dependency>
		<dependency>
			<groupId>com.impetus.kundera.client</groupId>
			<artifactId>kundera-mongo</artifactId>
			<version>2.11</version>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.impetus.kundera.client</groupId>
			<artifactId>kundera-rest</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.impetus.kundera.client</groupId>
			<artifactId>kundera-cassandra-pelops</artifactId>
			<version>${project.version}</version>
			<scope>test</scope>
		</dependency>

	      <!-- JAX-RS Libraries -->
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.18</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-core</artifactId>
			<version>1.18</version>
		</dependency>
	       <dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-servlet</artifactId>
			<version>1.18</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-json</artifactId>
			<version>1.18</version>
		</dependency>
  	       <dependency>
			<groupId>org.fusesource.restygwt</groupId>
			<artifactId>restygwt</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-servlet</artifactId>
			<version>2.5.1</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-user</artifactId>
			<version>2.5.1</version>
			<scope>provided</scope>
		</dependency>
       </dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<testSourceDirectory>test</testSourceDirectory>
		<resources>
			<resource>
				<directory>src</directory>
				<excludes>
					<exclude>**/*.java</exclude>
				</excludes>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
	 			  <source>1.6</source>
				  <target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
      <execution>
        <id>copy-dependencies</id>
        <phase>process-resources</phase>
        <goals>
          <goal>copy-dependencies</goal>
        </goals>
        <configuration>
          <outputDirectory>${basedir}/war/WEB-INF/lib/</outputDirectory>
          <excludeArtifactIds>gwt-user,gwt-dev,gwt-resty</excludeArtifactIds>
        </configuration>
      </execution>
    </executions>
  </plugin>
</plugins>
</build>

  1. Run the following command on the terminal : mvn clean install and then mvn eclipse:clean eclipse:eclipse After refreshing and building the project in eclipse reset the Google's web tool kit settings for project. web toolkit settings

  2. In order to start using Kundera add the following lines to file DataKeeper.gwt.xml

<inherits name='org.fusesource.restygwt.RestyGWT'/>
  <inherits name="com.google.gwt.json.JSON" />
  1. We will access Kundera using Rest. In order to do so we need to extend the methods defined in Rest classes and put those classes in client folder of your project. Sample class for same needs to be created in client folder and methods have to be defined in following manner :
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

//import javax.ws.rs.core.Context;
//import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.RestService;

import com.impetus.kundera.rest.common.Constants;

@Path("rest/kundera/api")
public interface KunderaService extends RestService
{

    @GET
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/application/{persistenceUnits}")
    public void getApplicationToken(@PathParam("persistenceUnits") String persistenceUnits
    		, MethodCallback<Object> callback);
    
    @DELETE
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/application")
    public void closeApplication(@HeaderParam(Constants.APPLICATION_TOKEN_HEADER_NAME) String applicationToken
    		, MethodCallback<Object> callback);

       
    @GET
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/session")
    public void getSessionToken(@HeaderParam(value = "x-at") String applicationToken
    		, MethodCallback<Object> callback);
    
    

    @DELETE
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/session")
    public void deleteSession(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken
    		, MethodCallback<Object> callback);
    
    @PUT
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/session")
    public void flush(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken
    		, MethodCallback<Object> callback);

   
    @POST
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/crud/{entityClass}")
    public void insert(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,
            @PathParam("entityClass") String entityClassName, String input,
            MethodCallback<Object> callback);

    @GET
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/crud/{entityClass}/{id}")
    public void find(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,
            @PathParam("entityClass") String entityClassName, @PathParam("id") String id,
            MethodCallback<Object> callback);

    @DELETE
    @Consumes(MediaType.APPLICATION_JSON )
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/crud/{entityClass}/delete/{id}")
    public void delete(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,
            @PathParam("entityClass") String entityClassName, @PathParam("id") String id,
                       MethodCallback<Object> callback);

    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
    @Path("/crud/{entityClass}")
    public void update(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,
            @PathParam("entityClass") String entityClassName, String input,
                     MethodCallback<Object> callback);

}
  1. Create entity classes in the project.
@Entity
@Table(name = "USER")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@IndexCollection(columns = { @Index(name = "preference"), @Index(name = "personalDetail"),@Index(name = "professionalDetail") })
public class UserCassandra
{

    @Id
    @Column(name = "USER_ID")
    private String userId;

    // Embedded object, will persist co-located
    @Embedded
    private PersonalDetailCassandra personalDetail;

    // Embedded object, will persist co-located
    @Embedded
    private ProfessionalDetailCassandra professionalDetail;

    // Element collection, will persist co-located
    @ElementCollection
    @CollectionTable(name = "tweeted")
    private List<TweetCassandra> tweets;

    // One to many, will be persisted separately
    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
    @JoinColumn(name = "FRIEND_ID")
    private List<UserCassandra> friends; // List of users whom I follow

    // One to many, will be persisted separately
    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
    @JoinColumn(name = "FOLLOWER_ID")
    private List<UserCassandra> followers; // List of users who are following me

    // One-to-one, will be persisted separately
    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
    @JoinColumn(name = "PREFERENCE_ID")
   // @XmlTransient
    private PreferenceCassandra preference;

    // One to many, will be persisted separately
    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
    @JoinColumn(name = "USER_ID")
    private Set<ExternalLinkCassandra> externalLinks;
    
    @Column(name = "USER_IMAGE")
    private byte[] userImage;

  1. In order to interact with them first create objects of your service classes :
      private final static KunderaService ks = GWT.create(KunderaService.class);

     private final static KunderaJPAQueryService kjs = GWT.create(KunderaJPAQueryService.class);

     private final static KunderaNativeQueryService kns = GWT.create(KunderaNativeQueryService.class);

     private static String applicationToken;

    private static String sessionToken;
  1. And then in order to invoke perform operations on your data using Kundera : Invoke the methods like this :
private static void getApplicationToken(String persistentUnit) {
		ks.getApplicationToken(persistentUnit, new MethodCallback<Object>() {
			@Override
			public void onSuccess(Method method, Object response) {
				sessionToken = response.toString();
				setSession(sessionToken);
				if(Cookies.isCookieEnabled()){
				   Cookies.setCookie(SESSION_COOKIE_NAME, sessionToken);
				 }
				returnResponse(response.toString());
			}

			@Override
			public void onFailure(Method method, Throwable exception) {
				returnResponse(exception.getMessage());
				GWT.log(exception.getMessage());

			}

			public String returnResponse(String resp) {
				return resp;
			}

		});

	}

  1. To start performing data operations using Kundera via GWT you must first create a session token by invoking getApplicationToken Method which initializes EMF and then you can invoke the rest calls using the session token.

  2. The request objects should be json encoded objects and response retrieved will also be same :

Sample Encoded response and objects sent across : Request for persisting a sample User entity object:

{"externalLinks":[{"extLinkId":"L2","linkAddress":"http://linkedin.com/in/devilmate","linkType":"LinkedIn"},{"extLinkId":"L1","linkAddress":"http://facebook.com/coolnerd","linkType":"Facebook"}],"followers":[{"personalDetail":{"name":"Paulo","password":"password1","personalDetailId":"0573c5e5-6c87-4f5d-ab8d-9d0a637a78ec","relationshipStatus":"married"},"userId":"0004"},{"personalDetail":{"name":"Vivek","password":"password1","personalDetailId":"fcef1a5e-614c-47f6-a6fc-604589985187","relationshipStatus":"married"},"userId":"0005"},{"personalDetail":{"name":"Kuldeep","password":"password1","personalDetailId":"e8f97d7c-fd3f-4223-bbb8-cea5972a6087","relationshipStatus":"single"},"userId":"0006"}],"friends":[{"personalDetail":{"name":"John","password":"password1","personalDetailId":"fcf6a180-abd2-4b19-8851-cd21a32debd3","relationshipStatus":"married"},"userId":"0002"},{"personalDetail":{"name":"Mary","password":"password1","personalDetailId":"cce70ddc-2578-45fa-b66c-dd9a25d1cca6","relationshipStatus":"married"},"userId":"0003"},{"personalDetail":{"name":"Shaheed","password":"password1","personalDetailId":"0a7355b8-5ca7-4611-8f4d-cc0524f6e2b6","relationshipStatus":"single"},"userId":"0007"}],"personalDetail":{"name":"Amresh","password":"password1","personalDetailId":"e702262f-e411-4692-8910-3be9bd3c920e","relationshipStatus":"married"},"preference":{"preferenceId":"P1","privacyLevel":"2","websiteTheme":"Motif"},"professionalDetail":{"accumulatedWealth":"123456789","age":"31","compliance":"10.0","departmentId":"23456789","digitalSignature":"8","enrolmentDate":"2012-10-31T12:42:21.111+05:30","enrolmentTime":"2012-10-31T12:42:22.222+05:30","exceptional":"true","grade":"67","graduationDay":"2012-08-04T16:47:47.777+05:30","height":"163.12","jobAttempts":"123456789","joiningDateAndTime":"2012-10-31T12:42:23.333+05:30","monthlySalary":"7.23452342343","rating":"5","uniqueId":"3634521523423","yearsSpent":"2"},"tweets":[{"body":"Here is my first tweet","device":"Web","tweetId":"3e27556a-4b17-4638-8af0-06a382a08f71"},{"body":"Second Tweet from me","device":"Mobile","tweetId":"7202d6fe-8570-44c9-947b-0175cf8500f4"}],"userId":"0001"}

Response for a sample Book object:

{book:{"author":"KK","isbn":"123","publication":"first lc"},{"author":"chhavi","isbn":"1111111122"}}
Clone this wiki locally