vulab | Open Source IT Training, Java, JEE, Spring Framework, Hibernate, JPA, Big Data, JEE, Hadoop, Spring, Hibernate, Android, IOS, Cloudera, Hortonworks, Big Insights

vulab We provide hands-on training in Java, Big Data, Hadoop, Sqoop, Hive, Impala, Map Reduce, Cloudera, Horton Works, IBM Big Insights, J2ee, Spring Framework, Hibernate, JPA, Android, Apple ios, Java script, HTML5, Database Development, SAP, .NET, Web Development, Quality Assurance, Mobile application development etc....
WE KEEP IT PROFESSIONALS TRAINED AND EMPLOYED.

Posted on 29 April 2017 by Srinivas Nelakuditi

Twitter Feed to Apache Hive using Apache Flume

Step 1: CREATE Folder in HDFS to load Tweet Data from Twitter

Create a folder in HDFS
hadoop fs -mkdir /demo/tweets

Step 2: Configure Flume by creating a Flume Configuration file with source, sink and channel

NOTE: Please get your own credentials for twitter by registering at twitter.com as a developer. Replace the xxxxxxxxxxx in the configuration below with your own credentials.

Create a file called twitter.conf with the following contents

TwitterAgent.sources = Twitter
TwitterAgent.channels = MemChannel
TwitterAgent.sinks = HDFS

# Describing/Configuring the source
TwitterAgent.sources.Twitter.type = org.apache.flume.source.twitter.TwitterSource

TwitterAgent.sources.Twitter.consumerKey=xxxxxxxxxxx
TwitterAgent.sources.Twitter.consumerSecret=xxxxxxxxxxx
TwitterAgent.sources.Twitter.accessToken=xxxxxxxxxxx
TwitterAgent.sources.Twitter.accessTokenSecret=xxxxxxxxxxx
TwitterAgent.sources.Twitter.keywords=hadoop, spark, apache spark, java, unix, linux, tesla, trump
# Describing/Configuring the sink

TwitterAgent.sources.Twitter.keywords= Vulab,BigData,Apache Spark, Spark Streaming,Data Science

TwitterAgent.sinks.HDFS.channel=MemChannel
TwitterAgent.sinks.HDFS.type=hdfs
TwitterAgent.sinks.HDFS.hdfs.path=hdfs://sandbox.hortonworks.com:8020/demo/tweets
TwitterAgent.sinks.HDFS.hdfs.fileType=DataStream
TwitterAgent.sinks.HDFS.hdfs.writeformat=Text
TwitterAgent.sinks.HDFS.hdfs.batchSize=1000
TwitterAgent.sinks.HDFS.hdfs.rollSize=0
TwitterAgent.sinks.HDFS.hdfs.rollCount=10000
TwitterAgent.sinks.HDFS.hdfs.rollInterval=600

TwitterAgent.channels.MemChannel.type=memory
TwitterAgent.channels.MemChannel.capacity=10000
TwitterAgent.channels.MemChannel.transactionCapacity=1000

TwitterAgent.sources.Twitter.channels = MemChannel
TwitterAgent.sinks.HDFS.channel = MemChannel

 

Step 3: Start Flume Agent to load data from Twitter feed to HDFS Folder

Execute flume

flume-ng agent -n TwitterAgent -f twitter.conf

 

Step 4: Analyze the data in HDFS Folder

After a few minutes you should have tweet data populated in HDFS folder /demo/tweets

Step 5:

Analyze the tweet files stored under /demo/tweets in HDFS

[root@sandbox ~]# hadoop fs -ls /demo/tweets
Found 10 items
-rw-r–r–   1 root hdfs    1151525 2017-04-29 22:02 /demo/tweets/FlumeData.1493503276896
-rw-r–r–   1 root hdfs     980837 2017-04-29 22:03 /demo/tweets/FlumeData.1493503337957
-rw-r–r–   1 root hdfs     991589 2017-04-29 22:04 /demo/tweets/FlumeData.1493503398855
-rw-r–r–   1 root hdfs    1002683 2017-04-29 22:05 /demo/tweets/FlumeData.1493503459830
-rw-r–r–   1 root hdfs     947843 2017-04-29 22:06 /demo/tweets/FlumeData.1493503519964
-rw-r–r–   1 root hdfs     969875 2017-04-29 22:07 /demo/tweets/FlumeData.1493503580889
-rw-r–r–   1 root hdfs     927216 2017-04-29 22:08 /demo/tweets/FlumeData.1493503641935
-rw-r–r–   1 root hdfs     978663 2017-04-29 22:09 /demo/tweets/FlumeData.1493503702912
-rw-r–r–   1 root hdfs     972084 2017-04-29 22:10 /demo/tweets/FlumeData.1493503763948
-rw-r–r–   1 root hdfs     696234 2017-04-29 22:11 /demo/tweets/FlumeData.1493503825045

 

NOTE: Flume is a good tool to get tweets from twitter to HDFS. But we suggest using HDF or Apache NIFI for loading tweets from twitter to HDFS or Hive for analytics. You can read more about NIFI here.

 

Enjoy your coding. If you would like to have Vulab’s BigData team to work for you or if you want to get trained by us. Please contact us for Hadoop Training

0 Comments

Posted on 11 March 2017 by Srinivas Nelakuditi

REST Web Services With Java Spring Framework Part 6

In the last part of this series, you have built a web service with Jersey, Spring Framework and Spring Boot.

In this part you will learn to integrate Swagger with REST Web Services.

Swagger will help in automatically documenting your web services, publish your documents and easily allows you to test your web services.

swagger

0 Comments

Posted on 11 March 2017 by Srinivas Nelakuditi

Spring Framework REST Web Services Tutorials

Please use the following tutorials to master Spring Framework with REST

REST Web Services with Java Part 1

REST Web Services with Java Part 2

REST Web Services with Java Part 3

 

 

REST Web Services with Java Part 4

 

REST Web Services with Java Part 5

0 Comments

Posted on 08 March 2017 by Srinivas Nelakuditi

REST Web Services with Java Part 5

In Part 4 you have created a maven project in Eclipse IDE.

Update your pom.xml with the following:

<?xml version=”1.0″ encoding=”UTF-8″?>
<project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
    xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.vulab</groupId>
    <artifactId>VULAB-REST-WEB-SERVICE</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

Create Application.java class to boot strap Spring Framework

package com.vulab.code;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        
    }

}

 

Configure a class for Jersey Configuration (JAX-RS) as RESTConfiguration.java

package com.vulab.code;

import org.glassfish.jersey.server.ResourceConfig;

import org.springframework.stereotype.Component;

@Component
public class RESTConfiguratoin extends ResourceConfig {

    public RESTConfiguratoin() {
        register(RESTEndpoint.class);
        
    }

}

 

Create a REST endpoint RESTEndpoint.java

package com.vulab.code;

import javax.validation.constraints.NotNull;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import org.springframework.stereotype.Component;

@Component
@Path(“/api/v1/simple”)
public class RESTEndpoint {

    @GET
    public String helloworld(@QueryParam(“input”) @NotNull String input) {
        return new StringBuilder(“Hello World ” + input).toString();
    }

}

 

Run Application.java to start your REST web service.

REST web service will start on port 8080 using Embedded Tomcat Server.

Browse to the URL:

http://localhost:8080/api/v1/simple?input=vulab

You will see the out put as:

Hello World vulab

 

You have successfully created and tested a Java REST Web Service using JAX-RS standard and Jersey Implementation.

 

 

1 Comment

Posted on 07 March 2017 by Srinivas Nelakuditi

Oozie Job Scheduling for Hive using Coordinator and Workflow

Let us create a Coordinator Job for Oozie.

The job will run a Hive script at every 5 minute interval.

Create a file job.properties

nameNode=hdfs://ip-10-74-66-159.vulab.com:8020
jobTracker=ip-10-74-66-190.vulab.com:8050

userName=srinivas
script_name_external = ${nameNode}/user/${userName}/hive_scripts/external.hive
database=dev_stg

oozie.use.system.libpath=true

 

Create a file workflow.xml

<workflow-app xmlns = “uri:oozie:workflow:0.4” name = “simple-Workflow”>
<start to = “Create_External_Table” />
<action name = “Create_External_Table”>
<hive xmlns = “uri:oozie:hive-action:0.4”>
<job-tracker>${jobTracker}</job-tracker>
<name-node>${nameNode}</name-node>
<script>${script_name_external}</script>
</hive>
<ok to = “end” />
<error to = “kill_job” />
</action>

<kill name = “kill_job”>
<message>Job failed</message>
</kill>
<end name = “end” />
</workflow-app>

Create a file coordinator.xml file

 

 <coordinator-app xmlns="uri:oozie:coordinator:0.2" name="create_table_hive" 
frequency="5 * * * *" start="2017-02-01T08:00Z" 
end ="2027-02-01T08:00Z" timezone="America/Los_Angeles">
   
   <controls>
      <timeout>1</timeout>
      <concurrency>1</concurrency>
      <execution>FIFO</execution>
      <throttle>1</throttle>
   </controls>
   
   <action>
      <workflow>
         <app-path>hdfs://ip-10-74-66-159.vulab.com:8020/user/srinivas/workflow.xml</app-path>
      </workflow>
   </action>
	
</coordinator-app>

 

Create a file called external.hive

CREATE TABLE IF NOT EXISTS dev_stg.external_table(
   name string,
   age int,
   address string,
   zip int
)
row format delimited
fields terminated by ','
stored as textfile;
  • Save the file job.properties in /home/srinivas in your linux home folder
  • Save the file coordinator.xml in /user/srinivas in hdfs folder using hdfs fs -put coordinator.xml /user/srinivas
  • Save the file workflow.xml in /user/srinivas in hdfs folder using hdfs fs -put workflow.xml /user/srinivas
  • Save the file external.hive in /user/srinivas in hdfs folder using hdfs fs -put external.hive /user/srinivas

    Run the command to submit the job for scheduling:

oozie job -oozie http://ip-10-74-66-190.vulab.com:11000/oozie/ -config /home/srinivas/job.properties -D oozie.coord.application.path=hdfs://ip-10-74-66-159.vulab.com:8020/user/srinivas/coordinator.xml -run

To check the status of the job:
http://ip-10-74-66-190.vulab.com:11000/oozie/

To kill a job you can use.
oozie job -oozie http://ip-10-74-66-190.vulab.com:11000/oozie/ -kill 0000020-170307022626285-oozie-oozi-C

 

 

0 Comments

Posted on 06 March 2017 by Srinivas Nelakuditi

REST Web Services with Java Part 4

Let us create a REST Web Service with Java using JAX-RS Standard.

We will use the following stack:
1. JDK 8
2. Eclipse IDE
3. Apache Maven
4. Spring Framework
5. Spring Boot
6. Jersey as JAX-RS Implementation

STEP 1:
Install JDK 8 on your OS.
You can download and install JDK 8 from this link
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Alternatively you can type ‘JDK 8 download’ in Google and download and install JDK 8.

STEP 2:
Install Eclipse IDE on your OS.
Please download the 64 bit version of Eclipse IDE for Java EE Developers
https://www.eclipse.org/downloads/eclipse-packages/

Start your Eclipse IDE after the installation

STEP 3:
Create a Maven Project in Eclipse IDE
Create Maven Project in Eclipse

Let us build our RESTful web service in the next part.

0 Comments

Posted on 06 March 2017 by Srinivas Nelakuditi

REST Web Services with Java Part 3

Let us look at a sample web service code snippet created using JAX-RS annotations

package com.vulab.code;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;

// The Java class will be hosted at the URI path "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {

     // The Java method will process HTTP GET requests
     @GET
     @Produces("text/plain")
     public String helloWorldVulab() {
          return "Hello World Vulab";
      }
}


In the above code snippet. @Path annotation is having the value of /helloworld

If a client wants to call the method helloWorldVulab, They can just use this URL in the web browser.

http://example.com/helloworld

Because you are automatically making a HTTP GET request. You call above will match with the @PATH annotation value and as you are making a HTTP GET request, it matches with @GET annotation on method helloWorldVulab. The method executes and you can see ‘Hello World Vulab’ on the web browser. @Produces annotation will allow the method to send the text as plain text. You can even send JSON or XML back to the caller with the @Produces annotation.

0 Comments

Posted on 06 March 2017 by Srinivas Nelakuditi

REST Web Services with Java Part 2

Developing RESTful Web Services with Java using JAX-RS
JAX-RS is a Java programming language API designed to make it easy to develop applications that use the REST architecture.

REST Web Services

As a developer you can use JAX-RS annotations in your code to create a RESTful Java Web Service.

Following are the important JAX-RS annotations for building REST web services.

Annotation

Description

@Path

The @Path annotation’s value is a relative URI
path indicating where the Java class will be hosted: for example, /helloworld.
You can also embed variables in the URIs to make a URI
path template. For example, you could ask for the name of a user
and pass it to the application as a variable in the URI:
/helloworld/{username}.

@GET

The @GET annotation is a request method designator and corresponds to the similarly
named HTTP method. The Java method annotated with this request method designator will
process HTTP GET requests. The behavior of a resource is determined by the
HTTP method to which the resource is responding.

@POST

The @POST annotation is a
request method designator and corresponds to the similarly named HTTP method. The Java
method annotated with this request method designator will process HTTP POST requests. The
behavior of a resource is determined by the HTTP method to which the
resource is responding.

@PUT

The @PUT annotation is a request method designator and corresponds to
the similarly named HTTP method. The Java method annotated with this request method
designator will process HTTP PUT requests. The behavior of a resource is determined
by the HTTP method to which the resource is responding.

@DELETE

The @DELETE annotation
is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP DELETE
requests. The behavior of a resource is determined by the HTTP method to
which the resource is responding.

@HEAD

The @HEAD annotation is a request method designator and corresponds
to the similarly named HTTP method. The Java method annotated with this request
method designator will process HTTP HEAD requests. The behavior of a resource is
determined by the HTTP method to which the resource is responding.

@PathParam

The @PathParam
annotation is a type of parameter that you can extract for use in
your resource class. URI path parameters are extracted from the request URI, and
the parameter names correspond to the URI path template variable names specified in
the @Path class-level annotation.

@QueryParam

The @QueryParam annotation is a type of parameter that you can
extract for use in your resource class. Query parameters are extracted from the
request URI query parameters.

@Consumes

The @Consumes annotation is used to specify the MIME media
types of representations a resource can consume that were sent by the client.

@Produces

The
@Produces annotation is used to specify the MIME media types of representations a
resource can produce and send back to the client: for example, "text/plain".

@Provider

The @Provider
annotation is used for anything that is of interest to the JAX-RS runtime,
such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is
used to map an HTTP request entity body to method parameters. On the
response side, a return value is mapped to an HTTP response entity body
by using a MessageBodyWriter. If the application needs to supply additional metadata, such
as HTTP headers or a different status code, a method can return a
Response that wraps the entity and that can be built using Response.ResponseBuilder.

0 Comments

Posted on 06 March 2017 by Srinivas Nelakuditi

REST Web Services with Java Part 1

REST is equal to REpresentational State Transfer.
REST as a web standard is created in year 2000.
REST web services uses HTTP protocol for data communication between source and destination.

rest web services java

In a REST web service. Every database table on the server is a resource. A client can access the resource on the server using standard HTTP Methods.

    HTTP GET used to READ
    HTTP PUT used to UPDATE
    HTTP POST used to CREATE
    HTTP DELETE used to DELETE
    HTTP OPTIONS to get supported methods

HTTP METHODS

In REST architecture each resource is represented by a unique URI.
REST uses various representations like XML,TEXT and JSON. JSON is the most widely used format for representing a resource.

Web Services built with above architecture are called RESTful Web Services.

0 Comments

Posted on 01 October 2015 by VPhani

Spring Data JPA with Java configuration

STEP ONE: Create New Dynamic Web Project In Eclipse IDE

We are creating a web project as we ultimately want to build a REST web service also. REST web service will use the Spring Data JPA layer to work with the database.

You will need JDK 7 or JDK 8 installed on your machine. You can get JDK 8 here.

If you do not have eclipse IDE, you can download Eclipse IDE for Java Developers from Eclipse.org/downloads page.

You will need Java or JEE web server or application server on your machine. You can use either tomcat 8 or JBoss server. Please download tomcat 8 from here. You can either download the 64 bit zip or 32 bit zip file from under the heading Core. Please unzip Tomcat 8 zip to a folder called C:/tomcat-8

Start Eclipse IDE. Please create a Dynamic Web Project using the menu.

 

Dynamic Web Project

Configure the project above to use your tomcat-8 located on your machine. Click Finish to compete creating a Dynamic Web Project.

STEP TWO: Convert the Dynamic Web  Project to add Maven capability

Right click on your project in eclipse and click on Configure and choose the option of Convert to Maven Project.

ConvertToMavenProject

Your project will be added with a file called pom.xml using which you can specify all your third party libraries.

STEP THREE: Create a New Data Model using MySQL Work Bench

Please install MySQL database on your machine and star the database. You can install mysql from this location.

Also please download and install MySQL Work bench on your machine. You can also download the mysql workbench from this location.

Start your MySQL Workbench. Create a new connection to your database.

Add new schema name “tomproject”

  1. Create a table called tomuser with Customer Id , FirstName, LastName and ProfilePicture entity.
  2. mysql
  3. Create package com.vulab.domain in Project .
  4. Create Customer domain object manually or using Hibernate tool
  5. package com.vulab.domain;import static javax.persistence.GenerationType.IDENTITY;import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.UniqueConstraint;@Entity
    @Table(name = “tomuser”, catalog = “tomproject”, uniqueConstraints = { @UniqueConstraint(columnNames = “email”) })
    public class Customer implements java.io.Serializable {/**
    *
    */
    private static final long serialVersionUID = 1L;
    private int customerId;
    private String firstname;
    private String lastName;
    private String email;public Customer() {
    }@Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = “customer_id”, unique = true, nullable = false)
    public int getCustomerId() {
    return customerId;
    }public void setCustomerId(int customerId) {
    this.customerId = customerId;
    }@Column(name = “first_name”)
    public String getFirstname() {
    return firstname;
    }

    public void setFirstname(String firstname) {
    this.firstname = firstname;
    }

    @Column(name = “last_name”)
    public String getLastName() {
    return lastName;
    }

    public void setLastName(String lastName) {
    this.lastName = lastName;
    }

    @Column(name = “email”)
    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    }

  6. Create a package com.vulab.config and create a ConfigCustomer class to configure
    1. The datasource bean.
    2.  The entity manager factory bean.
    3. The transaction manager bean.
    4. Enable annotation-driven transaction management.
    5.  Spring Data JPA.
  7. package com.vulab.config;import java.util.Properties;import javax.persistence.EntityManagerFactory;import org.apache.tomcat.jdbc.pool.DataSource;
    import org.apache.tomcat.jdbc.pool.PoolProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
    import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration
    @ComponentScan(“com.vulab”)
    @EnableJpaRepositories(basePackages = { “com.vulab.repositories” })
    @EnableTransactionManagement
    public class ConfigCustomer {@Bean(destroyMethod = “close”)
    DataSource dataSource() {PoolProperties p = new PoolProperties();
    p.setUrl(“jdbc:mysql://localhost:3306/tomproject”);
    p.setDriverClassName(“com.mysql.jdbc.Driver”);
    p.setUsername(“root”);
    p.setPassword(“”);
    p.setJmxEnabled(true);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setValidationQuery(“SELECT 1”);
    p.setTestOnReturn(false);
    p.setValidationInterval(30000);
    p.setTimeBetweenEvictionRunsMillis(30000);
    p.setMaxActive(10);
    p.setInitialSize(10);
    p.setMaxWait(10000);
    p.setRemoveAbandonedTimeout(60);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setMinIdle(10);
    p.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    p.setJdbcInterceptors(“org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;”
    + “org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer”);
    DataSource datasource = new org.apache.tomcat.jdbc.pool.DataSource();
    datasource.setPoolProperties(p);return datasource;
    }@Bean
    public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setJpaProperties(buildHibernateProperties());
    factory.setPackagesToScan(“com.vulab.domain”);
    factory.setDataSource(dataSource());
    factory.afterPropertiesSet();

    return factory.getObject();
    }

    protected Properties buildHibernateProperties() {
    Properties hibernateProperties = new Properties();

    hibernateProperties.setProperty(“hibernate.dialect”, “org.hibernate.dialect.MySQL5InnoDBDialect”);
    hibernateProperties.setProperty(“hibernate.show_sql”, “true”);
    hibernateProperties.setProperty(“hibernate.use_sql_comments”, “false”);
    hibernateProperties.setProperty(“hibernate.format_sql”, “false”);
    hibernateProperties.setProperty(“hibernate.hbm2ddl.auto”, “update”);

    hibernateProperties.setProperty(“hibernate.generate_statistics”, “false”);

    hibernateProperties.setProperty(“javax.persistence.validation.mode”, “none”);

    // Audit History flags
    // hibernateProperties.setProperty(“org.hibernate.envers.store_data_at_delete”,
    // “true”);
    // hibernateProperties.setProperty(“org.hibernate.envers.global_with_modified_flag”,
    // “true”);

    return hibernateProperties;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory());
    return txManager;
    }

    }

  8. Create a package com.vulab.repositories and create a CustomerRepository class that extends Spring data JPA interface.
  9. package com.vulab.repositories;import java.util.List;import org.springframework.data.jpa.repository.JpaRepository;import com.vulab.domain.Customer;public interface CustomerRepository extends JpaRepository<Customer, Integer>{public List<Customer> getCustomerByEmailAndFirstName(String email, String firstName);}
  10. Create a folder Test and write Junit test case to test.
  11. import javax.transaction.Transactional;import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.context.transaction.TransactionConfiguration;import com.vulab.config.ConfigCustomer;
    import com.vulab.domain.Customer;
    import com.vulab.repositories.CustomerRepository;@RunWith(SpringJUnit4ClassRunner.class)
    @Transactional
    @ContextConfiguration(classes = ConfigCustomer.class)
    @TransactionConfiguration(transactionManager = “transactionManager”, defaultRollback = true)
    public class Customerrepotestcase {
    @Autowired
    CustomerRepository customerRepository;@Test
    public void testSaveCustomer() {
    Customer customer = new Customer();
    customer.setEmail(“phany@vulab.com”);
    customer.setFirstname(“Phani”);
    customer.setLastName(“gv”);customerRepository.save(customer);
    org.junit.Assert.assertTrue(customer.getCustomerId() > 0);
    }}
  12. pom.xml configuration for adding all depedencies
  13. <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
    xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
    <modelVersion>4.0.0</modelVersion>
    <groupId>CustomerProject</groupId>
    <artifactId>CustomerProject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies><dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>8.0.26</version>
    </dependency><!– Apache CXF Dependencies –>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>2.7.13</version>
    </dependency>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>2.7.13</version>
    </dependency>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http-jetty</artifactId>
    <version>2.7.13</version>
    </dependency>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>2.7.13</version>
    </dependency>
    <!– Jackson The JSON Producer dependency –>
    <dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.0.1</version>
    </dependency>
    <!– Spring DATA JPA –>
    <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.9.0.RELEASE</version>
    </dependency><!– Hibernate Core dependency –>
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.11.Final</version>
    </dependency>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    </dependency><dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.3.11.Final</version>
    </dependency><dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>juli</artifactId>
    <version>6.0.26</version>
    </dependency>
    <!– Spring dependencies –>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.1.7.RELEASE</version>
    </dependency><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.7.RELEASE</version>
    </dependency><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.1.7.RELEASE</version>
    </dependency>

    <dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>dbcp</artifactId>
    <version>6.0.44</version>
    </dependency>

    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.36</version>
    </dependency>
    </dependencies>
    <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
    <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
    <warSourceDirectory>WebContent</warSourceDirectory>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
    </plugin>
    <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
    <source>1.8</source>
    <target>1.8</target>
    </configuration>
    </plugin>
    </plugins>
    </build>
    </project>

0 Comments