# Needed if IPC socket file located on windows OS
#ethereum.node.os=windows
================================================
FILE: examples/basic-examples/kundera-ethereum-example/src/main/resources/logback.xml
================================================
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/pom.xml
================================================
4.0.0
com.impetus.kundera.ethereum.webapp
kundera-ethereum-webapp
0.0.1-SNAPSHOT
jar
kundera-ethereum-webapp
http://maven.apache.org
UTF-8
org.springframework.boot
spring-boot-starter-parent
1.5.8.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-tomcat
javax.servlet
jstl
org.apache.tomcat.embed
tomcat-embed-jasper
com.impetus.kundera.client
kundera-cassandra
3.12-SNAPSHOT
com.impetus.kundera.client
kundera-ethereum
3.13
org.springframework
spring-orm
org.springframework
spring-web
com.fasterxml.jackson.core
jackson-databind
2.9.2
com.fasterxml.jackson.core
jackson-core
com.fasterxml.jackson.core
jackson-annotations
com.fasterxml.jackson.core
jackson-core
2.9.2
com.fasterxml.jackson.core
jackson-annotations
2.9.2
junit
junit
3.8.1
test
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/Application.java
================================================
package com.impetus.kundera.ethereum.webapp.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@ComponentScan(basePackages = "com.impetus.kundera.ethereum.webapp")
@Import({ BeanConfig.class, WebConfig.class })
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer
{
private static Class applicationClass = Application.class;
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
{
return application.sources(applicationClass);
}
}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/ApplicationInitializer.java
================================================
package com.impetus.kundera.ethereum.webapp.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class ApplicationInitializer implements WebApplicationInitializer
{
public void onStartup(ServletContext container) throws ServletException
{
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/BeanConfig.java
================================================
package com.impetus.kundera.ethereum.webapp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
public class BeanConfig
{
@Bean
public InternalResourceViewResolver setupViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/ui/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/WebConfig.java
================================================
package com.impetus.kundera.ethereum.webapp.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter
{
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/*.js/**").addResourceLocations("/ui/static/");
registry.addResourceHandler("/*.css/**").addResourceLocations("/ui/static/");
}
}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/controller/EthereumController.java
================================================
package com.impetus.kundera.ethereum.webapp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.impetus.kundera.ethereum.webapp.dao.EthereumDao;
@Controller
public class EthereumController
{
@Autowired
EthereumDao ethereumDao;
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView root()
{
ModelAndView model = new ModelAndView();
model.setViewName("home");
return model;
}
@RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home()
{
ModelAndView model = new ModelAndView();
model.setViewName("home");
return model;
}
@RequestMapping(value = "/import", method = RequestMethod.POST)
public ModelAndView importBlocks(@RequestParam("from_block") String from, @RequestParam("to_block") String to)
{
ModelAndView model = new ModelAndView();
ethereumDao.importBlocks(Long.parseLong(from), Long.parseLong(to));
model.addObject("importStatus", "Import of blocks from " + from + " to " + to + " is successful");
model.setViewName("home");
return model;
}
@RequestMapping(value = "/queryresult", method = RequestMethod.POST)
public ModelAndView queryBlocks(@RequestParam String query)
{
ModelAndView model = new ModelAndView();
List res = ethereumDao.runJPAQuery(query);
model.addObject("result", res);
model.setViewName("queryresult");
return model;
}
}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/dao/EthereumDao.java
================================================
package com.impetus.kundera.ethereum.webapp.dao;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.stereotype.Service;
import com.impetus.kundera.blockchain.ethereum.BlockchainImporter;
@Service
public class EthereumDao
{
private static BlockchainImporter importer = BlockchainImporter.initialize();
public void importBlocks(long from, long to)
{
importer.importBlocks(BigInteger.valueOf(from), BigInteger.valueOf(to));
}
public List runJPAQuery(String query)
{
EntityManager em = BlockchainImporter.getKunderaWeb3jClient().getEntityManager();
Query q = (Query) em.createQuery(query);
return q.getResultList();
}
}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/dao/UserDao.java
================================================
//package com.impetus.kundera.ethereum.webapp.dao;
//
//import javax.persistence.EntityManager;
//import javax.persistence.EntityManagerFactory;
//import javax.persistence.PersistenceUnit;
//
//import org.springframework.stereotype.Service;
//
//import com.impetus.kundera.ethereum.webapp.model.User;
//
//@Service
//public class UserDao
//{
// @PersistenceUnit(unitName = "cassandra_pu")
// EntityManagerFactory entityManagerFactory;
//
// public User addUser()
// {
// User user = new User();
// user.setEmail("johndoe123@gmail.com");
// user.setName("John Doe");
// user.setAddress("Bangalore, Karnataka");
// EntityManager entityManager = entityManagerFactory.createEntityManager();
// entityManager.persist(user);
// entityManager.close();
// return user;
// }
//
// public User getUserById(String Id)
// {
// EntityManager entityManager = entityManagerFactory.createEntityManager();
// User User = entityManager.find(User.class, Id);
// return User;
// }
//
// public EntityManagerFactory getEntityManagerFactory()
// {
// return entityManagerFactory;
// }
//
// public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory)
// {
// this.entityManagerFactory = entityManagerFactory;
// }
//}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/resources/kundera-ethereum.properties
================================================
database.type=cassandra
database.host=localhost
database.port=9160
database.name=qwery
## generate Block and Transaction tables
schema.auto.generate=true
## Drop existing tables
schema.drop.existing=true
## RPC HTTP end point or IPC socket file location or infura end point can be specified
#ethereum.node.endpoint=http://localhost:8545/
#ethereum.node.endpoint=/home/dev/ethereum/geth.ipc
ethereum.node.endpoint=https://mainnet.infura.io/1234
# Needed if IPC socket file located on windows OS
#ethereum.node.os=windows
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/webapp/ui/jsp/dashboard.jsp
================================================
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Spring Boot Example
User Details
${user.name}
${user.email}
${user.address}
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/webapp/ui/jsp/home.jsp
================================================
================================================
FILE: examples/basic-examples/kundera-ethereum-webapp/src/main/webapp/ui/jsp/queryresult.jsp
================================================
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Spring Boot Example
Query Result
${result.blockNumber}
${result.from}
${result.value}
================================================
FILE: examples/basic-examples/kundera-hbase-example/pom.xml
================================================
4.0.0
com.impetus.kundera
kundera-hbase-example
jar
1.0
kundera-hbase-example
http://maven.apache.org
3.13
com.impetus.kundera.client
kundera-hbase-v2
${kundera.version}
junit
junit
4.12
test
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
================================================
FILE: examples/basic-examples/kundera-hbase-example/src/main/java/com/impetus/kundera/entities/Person.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* The Class Person.
*/
@Entity
@Table(name = "PERSON")
public class Person
{
/** The person id. */
@Id
@Column(name = "PERSON_ID")
private String personId;
/** The person name. */
@Column(name = "PERSON_NAME")
private String personName;
/** The age. */
@Column(name = "AGE")
private int age;
/**
* Gets the person id.
*
* @return the person id
*/
public String getPersonId()
{
return personId;
}
/**
* Sets the person id.
*
* @param personId
* the new person id
*/
public void setPersonId(String personId)
{
this.personId = personId;
}
/**
* Gets the person name.
*
* @return the person name
*/
public String getPersonName()
{
return personName;
}
/**
* Sets the person name.
*
* @param personName
* the new person name
*/
public void setPersonName(String personName)
{
this.personName = personName;
}
/**
* Gets the age.
*
* @return the age
*/
public int getAge()
{
return age;
}
/**
* Sets the age.
*
* @param age
* the new age
*/
public void setAge(int age)
{
this.age = age;
}
}
================================================
FILE: examples/basic-examples/kundera-hbase-example/src/main/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
================================================
FILE: examples/basic-examples/kundera-hbase-example/src/test/java/com/impetus/kundera/CRUDTest.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.kundera.entities.Person;
/**
* The Class CRUDTest.
*/
public class CRUDTest
{
/** The Constant PU. */
private static final String PU = "hbase_pu";
/** The emf. */
private static EntityManagerFactory emf;
/** The em. */
private EntityManager em;
/**
* Sets the up before class.
*
* @throws Exception
* the exception
*/
@BeforeClass
public static void SetUpBeforeClass() throws Exception
{
emf = Persistence.createEntityManagerFactory(PU);
}
/**
* Sets the up.
*
* @throws Exception
* the exception
*/
@Before
public void setUp() throws Exception
{
em = emf.createEntityManager();
}
/**
* Test crud operations.
*
* @throws Exception
* the exception
*/
@Test
public void testCRUDOperations() throws Exception
{
testInsert();
testMerge();
testRemove();
}
/**
* Test insert.
*
* @throws Exception
* the exception
*/
private void testInsert() throws Exception
{
Person p = new Person();
p.setPersonId("101");
p.setPersonName("dev");
p.setAge(24);
em.persist(p);
Person person = em.find(Person.class, "101");
Assert.assertNotNull(person);
Assert.assertEquals("101", person.getPersonId());
Assert.assertEquals("dev", person.getPersonName());
}
/**
* Test merge.
*/
private void testMerge()
{
Person person = em.find(Person.class, "101");
person.setPersonName("devender");
em.merge(person);
Person p1 = em.find(Person.class, "101");
Assert.assertEquals("devender", p1.getPersonName());
}
/**
* Test remove.
*/
private void testRemove()
{
Person p = em.find(Person.class, "101");
em.remove(p);
Person p1 = em.find(Person.class, "101");
Assert.assertNull(p1);
}
/**
* Tear down.
*
* @throws Exception
* the exception
*/
@After
public void tearDown() throws Exception
{
em.close();
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
if (emf != null)
{
emf.close();
emf = null;
}
}
}
================================================
FILE: examples/basic-examples/kundera-mongodb-example/pom.xml
================================================
4.0.0
com.impetus.kundera
kundera-mongodb-example
jar
1.0
kundera-mongodb-example
http://maven.apache.org
3.13
com.impetus.kundera.client
kundera-mongo
${kundera.version}
junit
junit
4.12
test
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
================================================
FILE: examples/basic-examples/kundera-mongodb-example/src/main/java/com/impetus/kundera/entities/Person.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* The Class Person.
*/
@Entity
@Table(name = "PERSON")
public class Person
{
/** The person id. */
@Id
@Column(name = "PERSON_ID")
private String personId;
/** The person name. */
@Column(name = "PERSON_NAME")
private String personName;
/** The age. */
@Column(name = "AGE")
private int age;
/**
* Gets the person id.
*
* @return the person id
*/
public String getPersonId()
{
return personId;
}
/**
* Sets the person id.
*
* @param personId
* the new person id
*/
public void setPersonId(String personId)
{
this.personId = personId;
}
/**
* Gets the person name.
*
* @return the person name
*/
public String getPersonName()
{
return personName;
}
/**
* Sets the person name.
*
* @param personName
* the new person name
*/
public void setPersonName(String personName)
{
this.personName = personName;
}
/**
* Gets the age.
*
* @return the age
*/
public int getAge()
{
return age;
}
/**
* Sets the age.
*
* @param age
* the new age
*/
public void setAge(int age)
{
this.age = age;
}
}
================================================
FILE: examples/basic-examples/kundera-mongodb-example/src/main/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
================================================
FILE: examples/basic-examples/kundera-mongodb-example/src/test/java/com/impetus/kundera/CRUDTest.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.kundera.entities.Person;
/**
* The Class CRUDTest.
*/
public class CRUDTest
{
/** The Constant PU. */
private static final String PU = "mongo_pu";
/** The emf. */
private static EntityManagerFactory emf;
/** The em. */
private EntityManager em;
/**
* Sets the up before class.
*
* @throws Exception
* the exception
*/
@BeforeClass
public static void SetUpBeforeClass() throws Exception
{
emf = Persistence.createEntityManagerFactory(PU);
}
/**
* Sets the up.
*
* @throws Exception
* the exception
*/
@Before
public void setUp() throws Exception
{
em = emf.createEntityManager();
}
/**
* Test crud operations.
*
* @throws Exception
* the exception
*/
@Test
public void testCRUDOperations() throws Exception
{
testInsert();
testMerge();
testRemove();
}
/**
* Test insert.
*
* @throws Exception
* the exception
*/
private void testInsert() throws Exception
{
Person p = new Person();
p.setPersonId("101");
p.setPersonName("dev");
p.setAge(24);
em.persist(p);
Person person = em.find(Person.class, "101");
Assert.assertNotNull(person);
Assert.assertEquals("101", person.getPersonId());
Assert.assertEquals("dev", person.getPersonName());
}
/**
* Test merge.
*/
private void testMerge()
{
Person person = em.find(Person.class, "101");
person.setPersonName("devender");
em.merge(person);
Person p1 = em.find(Person.class, "101");
Assert.assertEquals("devender", p1.getPersonName());
}
/**
* Test remove.
*/
private void testRemove()
{
Person p = em.find(Person.class, "101");
em.remove(p);
Person p1 = em.find(Person.class, "101");
Assert.assertNull(p1);
}
/**
* Tear down.
*
* @throws Exception
* the exception
*/
@After
public void tearDown() throws Exception
{
em.close();
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
if (emf != null)
{
emf.close();
emf = null;
}
}
}
================================================
FILE: examples/basic-examples/polyglot/kundera-mongodb-kudu-example/pom.xml
================================================
4.0.0
com.impetus.kundera
kundera-mongodb-kudu-example
jar
1.0
kundera-mongodb-kudu-example
http://maven.apache.org
3.13
com.impetus.kundera.client
kundera-mongo
${kundera.version}
com.impetus.kundera.client
kundera-kudu
${kundera.version}
junit
junit
4.12
test
org.apache.maven.plugins
maven-compiler-plugin
3.5.1
1.7
1.7
================================================
FILE: examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/main/java/com/impetus/kundera/entities/Address.java
================================================
/*******************************************************************************
* * Copyright 2017 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* The Class Address.
*/
@Entity
@Table(name = "ADDRESS", schema = "kundera_mongo@mongo_pu")
public class Address
{
/** The address id. */
@Id
@Column(name = "ADDRESS_ID")
private String addressId;
/** The street. */
@Column(name = "STREET")
private String street;
/** The city. */
@Column(name = "CITY")
private String city;
/** The country. */
@Column(name = "COUNTRY")
private String country;
/**
* Instantiates a new address.
*/
public Address()
{
}
/**
* Instantiates a new address.
*
* @param addressId
* the address id
* @param street
* the street
* @param city
* the city
* @param country
* the country
*/
public Address(String addressId, String street, String city, String country)
{
this.addressId = addressId;
this.street = street;
this.city = city;
this.country = country;
}
/**
* Gets the address id.
*
* @return the address id
*/
public String getAddressId()
{
return addressId;
}
/**
* Sets the address id.
*
* @param addressId
* the new address id
*/
public void setAddressId(String addressId)
{
this.addressId = addressId;
}
/**
* Gets the street.
*
* @return the street
*/
public String getStreet()
{
return street;
}
/**
* Sets the street.
*
* @param street
* the new street
*/
public void setStreet(String street)
{
this.street = street;
}
/**
* Gets the city.
*
* @return the city
*/
public String getCity()
{
return city;
}
/**
* Sets the city.
*
* @param city
* the new city
*/
public void setCity(String city)
{
this.city = city;
}
/**
* Gets the country.
*
* @return the country
*/
public String getCountry()
{
return country;
}
/**
* Sets the country.
*
* @param country
* the new country
*/
public void setCountry(String country)
{
this.country = country;
}
}
================================================
FILE: examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/main/java/com/impetus/kundera/entities/Person.java
================================================
/*******************************************************************************
* * Copyright 2017 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.entities;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* The Class Person.
*/
@Entity
@Table(name = "PERSON", schema = "kundera_kudu@kudu_pu")
public class Person
{
/** The person id. */
@Id
@Column(name = "PERSON_ID")
private String personId;
/** The person name. */
@Column(name = "PERSON_NAME")
private String personName;
/** The age. */
@Column(name = "AGE")
private int age;
/** The addresses. */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ADDRESS_ID")
private List addresses;
/**
* Gets the addresses.
*
* @return the addresses
*/
public List getAddresses()
{
return addresses;
}
/**
* Sets the addresses.
*
* @param addresses
* the new addresses
*/
public void setAddresses(List addresses)
{
this.addresses = addresses;
}
/**
* Gets the person id.
*
* @return the person id
*/
public String getPersonId()
{
return personId;
}
/**
* Sets the person id.
*
* @param personId
* the new person id
*/
public void setPersonId(String personId)
{
this.personId = personId;
}
/**
* Gets the person name.
*
* @return the person name
*/
public String getPersonName()
{
return personName;
}
/**
* Sets the person name.
*
* @param personName
* the new person name
*/
public void setPersonName(String personName)
{
this.personName = personName;
}
/**
* Gets the age.
*
* @return the age
*/
public int getAge()
{
return age;
}
/**
* Sets the age.
*
* @param age
* the new age
*/
public void setAge(int age)
{
this.age = age;
}
}
================================================
FILE: examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/main/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.entities.Address
true
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.entities.Person
true
================================================
FILE: examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/test/java/com/impetus/kundera/CRUDTest.java
================================================
/*******************************************************************************
* * Copyright 2017 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.kundera.entities.Address;
import com.impetus.kundera.entities.Person;
/**
* The Class CRUDTest.
*/
public class CRUDTest
{
/** The Constant PU. */
private static final String PU = "mongo_pu,kudu_pu";
/** The emf. */
private static EntityManagerFactory emf;
/** The em. */
private EntityManager em;
/**
* Sets the up before class.
*
* @throws Exception
* the exception
*/
@BeforeClass
public static void SetUpBeforeClass() throws Exception
{
emf = Persistence.createEntityManagerFactory(PU);
}
/**
* Sets the up.
*
* @throws Exception
* the exception
*/
@Before
public void setUp() throws Exception
{
em = emf.createEntityManager();
}
/**
* Test crud operations.
*
* @throws Exception
* the exception
*/
@Test
public void testCRUDOperations() throws Exception
{
testInsert();
testMerge();
testRemove();
}
/**
* Test insert.
*
* @throws Exception
* the exception
*/
private void testInsert() throws Exception
{
Person p = new Person();
p.setPersonId("101");
p.setPersonName("dev");
p.setAge(24);
Address a1 = new Address("a1", "str1", "noida", "india");
Address a2 = new Address("a2", "str2", "bglr", "india");
List adds = new ArrayList();
adds.add(a1);
adds.add(a2);
p.setAddresses(adds);
em.persist(p);
Person person = em.find(Person.class, "101");
Assert.assertNotNull(person);
Assert.assertEquals("101", person.getPersonId());
Assert.assertEquals("dev", person.getPersonName());
Assert.assertEquals("india", person.getAddresses().get(0).getCountry());
}
/**
* Test merge.
*/
private void testMerge()
{
Person person = em.find(Person.class, "101");
person.setPersonName("devender");
em.merge(person);
Person p1 = em.find(Person.class, "101");
Assert.assertEquals("devender", p1.getPersonName());
}
/**
* Test remove.
*/
private void testRemove()
{
Person p = em.find(Person.class, "101");
em.remove(p);
Person p1 = em.find(Person.class, "101");
Assert.assertNull(p1);
}
/**
* Tear down.
*
* @throws Exception
* the exception
*/
@After
public void tearDown() throws Exception
{
em.close();
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
if (emf != null)
{
emf.close();
emf = null;
}
}
}
================================================
FILE: examples/container/jboss/data-keeper/pom.xml
================================================
4.0.0
com.impetus.kundera.examples
jboss
3.3-SNAPSHOT
com.impetus.kundera.examples
jboss-data-keeper
war
1.0-SNAPSHOT
data-keeper
http://maven.apache.org
UTF-8
3.0.5.RELEASE
3.3-SNAPSHOT
junit
junit
4.8.2
test
com.impetus.kundera.core
kundera-core
${kundera.version}
com.impetus.kundera.client
kundera-cassandra
${kundera.version}
io.netty
netty
com.impetus.kundera.client
kundera-mongo
${kundera.version}
javax.servlet
javax.servlet-api
3.0.1
provided
com.sun.faces
jsf-api
2.1.10
com.sun.faces
jsf-impl
2.1.10
jstl
jstl
1.2
org.primefaces
primefaces
3.3.1
commons-fileupload
commons-fileupload
1.3
commons-io
commons-io
2.4
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-orm
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-test
${spring.version}
data-keeper
maven-compiler-plugin
1.7
1.7
true
prime-repo
PrimeFaces Maven Repository
http://repository.primefaces.org
default
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentDownloadBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "documentDownloadBean")
@RequestScoped
public class DocumentDownloadBean
{
private int documentId;
public int getDocumentId()
{
return documentId;
}
public void setDocumentId(int documentId)
{
this.documentId = documentId;
}
/**
* Download file used for downloading photo.
*
* @param photoPath
* the photo path
*/
public void download()
{
DataKeeperService service = DataKeeperUtils.getService();
setDocumentId(Integer.parseInt(FacesUtils.getRequest().getParameter("documentId")));
DocumentInfo document = service.findDocumentByDocumentId(getDocumentId());
final HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
ServletOutputStream out = null;
try
{
out = response.getOutputStream();
out.write(document.getData(), 0, 4096);
}
catch (IOException e)
{
}
finally
{
if (out != null)
{
try
{
out.flush();
out.close();
}
catch (IOException e)
{
}
}
}
FacesContext.getCurrentInstance().responseComplete();
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentSearchBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
@ManagedBean(name = "documentSearchBean")
@RequestScoped
public class DocumentSearchBean
{
private String searchText;
private int searchBy;
private List documents;
public String getSearchText()
{
return searchText;
}
public void setSearchText(String searchText)
{
this.searchText = searchText;
}
public int getSearchBy()
{
return searchBy;
}
public void setSearchBy(int searchBy)
{
this.searchBy = searchBy;
}
public List getDocuments()
{
return documents;
}
public void setDocuments(List documents)
{
this.documents = documents;
}
public List search()
{
documents = new ArrayList();
DataKeeperService service = DataKeeperUtils.getService();
switch (SearchType.getSearchType(searchBy))
{
case ID:
documents = service.findDocumentByEmployeeId(getSearchText());
break;
case NAME:
documents = service.findDocumentByEmployeeName(getSearchText());
break;
}
return documents;
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentUploadBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "documentUploadBean")
@RequestScoped
public class DocumentUploadBean
{
public DocumentUploadBean()
{
}
public String handleFileUpload(FileUploadEvent event)
{
HttpSession session = FacesUtils.getSession();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
DataKeeperService service = DataKeeperUtils.getService();
UploadedFile file = event.getFile();
if (file != null)
{
DocumentInfo dataInfo = new DocumentInfo();
dataInfo.setData(file.getContents());
dataInfo.setDocumentName(file.getFileName());
dataInfo.setSize(file.getSize());
dataInfo.setOwnerName(employee.getEmployeeName());
dataInfo.setOwnerId(employee.getEmployeeId());
dataInfo.setUplodedDate(new Date());
service.insertData(dataInfo);
FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "successfully uploaded";
}
return "uploading fail";
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/EmployeeSearchBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.servlet.http.HttpSession;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "subordinateSearchBean")
@RequestScoped
public class EmployeeSearchBean
{
private List subordinates = new ArrayList();
private int managerId;
private int noOfYears;
private String searchText;
private int searchBy;
public String getSearchText()
{
return searchText;
}
public void setSearchText(String searchText)
{
this.searchText = searchText;
}
public int getSearchBy()
{
return searchBy;
}
public void setSearchBy(int searchBy)
{
this.searchBy = searchBy;
}
/**
* @return the managerName
*/
public int getManagerId()
{
return managerId;
}
/**
* @param managerName
* the managerName to set
*/
public void setManagerId(int managerId)
{
this.managerId = managerId;
}
public int getNoOfYears()
{
return noOfYears;
}
public void setNoOfYears(int noOfYears)
{
this.noOfYears = noOfYears;
}
public List getSubordinates()
{
return subordinates;
}
public void setSubordinates(List subordinates)
{
this.subordinates = subordinates;
}
public String searchSubordinates()
{
DataKeeperService service = DataKeeperUtils.getService();
setManagerId(Integer.parseInt(FacesUtils.getRequest().getParameter("managerId")));
List subordinates = service.findSubOrdinates(getManagerId());
if (subordinates != null)
{
this.subordinates = subordinates;
}
return "foundEmployess";
}
public String searchEmployee()
{
DataKeeperService service = DataKeeperUtils.getService();
Employee employee = null;
switch (SearchType.getSearchType(searchBy))
{
case ID:
employee = service.findEmployee(Integer.parseInt(getSearchText()));
break;
case NAME:
employee = service.findEmployeeByName(getSearchText());
break;
}
if (employee != null)
{
List employees = new ArrayList();
employees.add(employee);
this.subordinates = employees;
}
return "foundEmployess";
}
public String searchEmployeeByYearOfComplition()
{
DataKeeperService service = DataKeeperUtils.getService();
HttpSession session = FacesUtils.getSession();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
List employees = service.findEmployeeByDateOfJoining(getNoOfYears(), employee.getCompany());
if (employees != null)
{
this.subordinates = employees;
}
return "foundEmployess";
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/IncrementCounterBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.servlet.http.HttpSession;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.entities.SubordinatesCounter;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "incrementCounterBean")
@RequestScoped
public class IncrementCounterBean
{
private SubordinatesCounter counter = new SubordinatesCounter();
public IncrementCounterBean()
{
}
public SubordinatesCounter getCounter()
{
return counter;
}
public void setCounter(SubordinatesCounter counter)
{
this.counter = counter;
}
public String incrementCounter()
{
DataKeeperService service = DataKeeperUtils.getService();
HttpSession session = FacesUtils.getSession();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
counter.setEmployeeId(employee.getEmployeeId());
service.incrementCounter(counter);
return "success";
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/LoginBean.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.datakeeper.beans;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
/**
*
*
* @author amresh.singh
*/
@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean
{
private Employee employee = new Employee();
public LoginBean()
{
}
public Employee getEmployee()
{
return employee;
}
public void setEmployee(Employee employee)
{
this.employee = employee;
}
public String logOff()
{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You have successfully Logged off"));
session.invalidate();
return DataKeeperConstants.OUTCOME_LOGOFF_SUCCESSFUL;
}
public String deleteAccount()
{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
DataKeeperService service = DataKeeperUtils.getService();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
service.removeEmployee(employee);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account successfully deleted"));
session.invalidate();
return "Account successfully deleted";
}
public String authenticate()
{
String outcome = null;
// Validates Parameters
if (StringUtils.isBlank(employee.getEmployeeName()))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter your user name"));
outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
}
if (StringUtils.isBlank(employee.getPassword()))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter password"));
outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
}
if (StringUtils.isNotBlank(outcome))
{
return outcome;
}
else
{
DataKeeperService service = DataKeeperUtils.getService();
Employee foundEmployee = service.findEmployeeByName(employee.getEmployeeName());
boolean success = service.authenticateEmployee(foundEmployee, employee.getPassword());
if (!success)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Incorrect User Name/Password"));
outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
}
else
{
outcome = DataKeeperConstants.OUTCOME_LOGIN_SUCCESSFUL;
HttpSession session = FacesUtils.getSession();
session.setAttribute(DataKeeperConstants.EMPLOYEE, foundEmployee);
}
return outcome;
}
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/RegisterBean.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.datakeeper.beans;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FlowEvent;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
/**
*
*
* @author Kuldeep.Mishra
*/
@ManagedBean(name = "registerBean")
@RequestScoped
public class RegisterBean
{
private Employee employee = new Employee();
private int managerId;
public RegisterBean()
{
}
public Employee getEmployee()
{
return employee;
}
public void setEmployee(Employee employee)
{
this.employee = employee;
}
public int getManagerId()
{
return managerId;
}
public void setManagerId(int managerId)
{
this.managerId = managerId;
}
public String onFlowProcess(FlowEvent event)
{
return event.getNewStep();
}
public String save()
{
DataKeeperService service = DataKeeperUtils.getService();
Employee manager = service.findEmployee(managerId);
employee.setManager(manager);
employee.setTimestamp(employee.getJoiningDate().getTime());
service.insertEmployee(employee);
FacesMessage msg = new FacesMessage("SignUp Successful! Welcome, " + employee.getEmployeeName());
FacesContext.getCurrentInstance().addMessage(null, msg);
return "signUpSuccessful";
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/SearchType.java
================================================
/**
*
*/
package com.impetus.kundera.datakeeper.beans;
/**
* @author Kuldeep.Mishra
*
*/
enum SearchType
{
ID, NAME;
static SearchType getSearchType(int searchBy)
{
if (searchBy == 1)
{
return ID;
}
else if (searchBy == 0)
{
return NAME;
}
return null;
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDao.java
================================================
package com.impetus.kundera.datakeeper.dao;
import java.util.List;
import javax.persistence.EntityManager;
/**
* @author Kuldeep.Mishra
*
*/
public interface DataKeeperDao
{
EntityManager getEntityManager();
void closeEntityManager();
void clearEntityManager();
void shutDown();
void insert(Object entity);
void merge(Object entity);
void remove(Object entity);
T findById(Class entityClazz, Object id);
List> findByQuery(String Query);
List> findByQuery(String queryString, String paramater, Object parameterValue);
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDaoImpl.java
================================================
package com.impetus.kundera.datakeeper.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl;
/**
* @author Kuldeep.Mishra
*
*/
// @Transactional(propagation = Propagation.REQUIRED)
public class DataKeeperDaoImpl implements DataKeeperDao
{
/**
* logger used for logging statement.
*/
private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);
@PersistenceContext(unitName = "cassandra-pu,mongo-pu", type = PersistenceContextType.EXTENDED)
private EntityManager em;
public DataKeeperDaoImpl()
{
}
@Override
public void insert(Object entity)
{
em.persist(entity);
em.clear();
}
@Override
public void merge(Object entity)
{
em.merge(entity);
em.clear();
}
@Override
public void remove(Object entity)
{
em.remove(entity);
em.clear();
}
@Override
public T findById(Class entityClazz, Object id)
{
T results = em.find(entityClazz, id);
return results;
}
@Override
public List> findByQuery(String queryString)
{
log.info(queryString);
Query query = em.createQuery(queryString);
List> resultList = query.getResultList();
return resultList;
}
@Override
public List> findByQuery(String queryString, String paramater, Object parameterValue)
{
Query query = em.createQuery(queryString);
query.setParameter(paramater, parameterValue);
log.info(queryString);
List> resultList = query.getResultList();
return resultList;
}
@Override
public EntityManager getEntityManager()
{
return em;
}
@Override
public void closeEntityManager()
{
if (em != null)
{
em.close();
}
}
@Override
public void clearEntityManager()
{
if (em != null)
{
em.clear();
}
}
@Override
public void shutDown()
{
if (em != null)
{
em.close();
}
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/DocumentInfo.java
================================================
package com.impetus.kundera.datakeeper.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.primefaces.model.StreamedContent;
import com.impetus.kundera.datakeeper.utils.DataFormat;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* @author Kuldeep.Mishra
*
*/
@Entity
@Table(name = "DOCUMENT", schema = "datakeeper@mongo-pu")
@IndexCollection(columns = { @Index(name = "ownerName"), @Index(name = "ownerId"), @Index(name = "documentName") })
public class DocumentInfo
{
@Id
@Column(name = "DOCUMENT_ID")
@GeneratedValue()
private String dataId;
@Column(name = "EMPLOYEE_NAME")
private String ownerName;
@Column(name = "EMPLOYEE_ID")
private int ownerId;
@Column(name = "UPLOADED_DATE")
private Date uplodedDate;
@Column(name = "DOCUMENT_FORMAT")
private DataFormat dataFormat;
@Column(name = "DOCUMENT_NAME")
private String documentName;
@Column(name = "DATA")
private byte[] data;
private StreamedContent file;
@Column(name = "SIZE")
private long size;
/**
* @return the dataId
*/
public String getDataId()
{
return dataId;
}
/**
* @param dataId
* the dataId to set
*/
public void setDataId(String dataId)
{
this.dataId = dataId;
}
/**
* @return the ownerName
*/
public String getOwnerName()
{
return ownerName;
}
/**
* @param ownerName
* the ownerName to set
*/
public void setOwnerName(String ownerName)
{
this.ownerName = ownerName;
}
/**
* @return the ownerId
*/
public int getOwnerId()
{
return ownerId;
}
/**
* @param ownerId
* the ownerId to set
*/
public void setOwnerId(int ownerId)
{
this.ownerId = ownerId;
}
/**
* @return the uplodedDate
*/
public Date getUplodedDate()
{
return uplodedDate;
}
/**
* @param uplodedDate
* the uplodedDate to set
*/
public void setUplodedDate(Date uplodedDate)
{
this.uplodedDate = uplodedDate;
}
/**
* @return the dataFormat
*/
public DataFormat getDataFormat()
{
return dataFormat;
}
/**
* @param dataFormat
* the dataFormat to set
*/
public void setDataFormat(DataFormat dataFormat)
{
this.dataFormat = dataFormat;
}
public byte[] getData()
{
return data;
}
public void setData(byte[] data)
{
this.data = data;
}
public String getDocumentName()
{
return documentName;
}
public void setDocumentName(String documentName)
{
this.documentName = documentName;
}
public long getSize()
{
return size;
}
public void setSize(long size)
{
this.size = size;
}
public StreamedContent getFile()
{
return file;
}
public void addFile(StreamedContent file)
{
this.file = file;
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/Employee.java
================================================
package com.impetus.kundera.datakeeper.entities;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* @author Kuldeep.Mishra
*
*/
@Entity
@Table(name = "EMPLOYEE", schema = "datakeeper@cassandra-pu")
@IndexCollection(columns = { @Index(name = "employeeName"), @Index(name = "designation"), @Index(name = "experience"),
@Index(name = "joiningDate"), @Index(name = "currentProject"), @Index(name = "timestamp"),
@Index(name = "company") })
public class Employee
{
@Id
@Column(name = "EMPLOYEE_ID")
@GeneratedValue(strategy = GenerationType.TABLE)
private int employeeId;
@Column(name = "PASSWORD")
private String password;
@Column(name = "EMPLOYEE_NAME")
private String employeeName;
@Column(name = "EXPERIENCE")
private int experience;
@Column(name = "JOINING_DATE")
private Date joiningDate;
@Column(name = "DESIGNATION")
private String designation;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "MANAGER_ID")
private Employee manager;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "manager")
private List subordinates;
@Column(name = "PROJECT")
private String currentProject;
@Column(name = "COMPANY")
private String company;
@Column(name = "JOINING_TIMESTAMP")
private long timestamp;
public int getEmployeeId()
{
return employeeId;
}
public void setEmployeeId(int employeeId)
{
this.employeeId = employeeId;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmployeeName()
{
return employeeName;
}
public void setEmployeeName(String employeeName)
{
this.employeeName = employeeName;
}
public int getExperience()
{
return experience;
}
public void setExperience(int experience)
{
this.experience = experience;
}
public Date getJoiningDate()
{
return joiningDate;
}
public void setJoiningDate(Date joiningDate)
{
this.joiningDate = joiningDate;
}
public String getDesignation()
{
return designation;
}
public void setDesignation(String designation)
{
this.designation = designation;
}
public Employee getManager()
{
return manager;
}
public void setManager(Employee manager)
{
this.manager = manager;
}
public String getCurrentProject()
{
return currentProject;
}
public void setCurrentProject(String currentProject)
{
this.currentProject = currentProject;
}
public List getSubordinates()
{
return subordinates;
}
public void setSubordinates(List subordinates)
{
this.subordinates = subordinates;
}
public long getTimestamp()
{
return timestamp;
}
public void setTimestamp(long timestamp)
{
this.timestamp = timestamp;
}
public String getCompany()
{
return company;
}
public void setCompany(String company)
{
this.company = company;
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/SubordinatesCounter.java
================================================
package com.impetus.kundera.datakeeper.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "SUBORDINATES_COUNTER", schema = "datakeeper@cassandra-pu")
public class SubordinatesCounter
{
@Id
@Column(name = "EMPLOYEE_ID")
private int employeeId;
@Column(name = "SUBORDINATES_COUNTER")
private int noOfSubordinates;
public int getEmployeeId()
{
return employeeId;
}
public void setEmployeeId(int employeeId)
{
this.employeeId = employeeId;
}
public int getNoOfSubordinates()
{
return noOfSubordinates;
}
public void setNoOfSubordinates(int noOfSubordinates)
{
this.noOfSubordinates = noOfSubordinates;
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperService.java
================================================
package com.impetus.kundera.datakeeper.service;
import java.util.List;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.entities.SubordinatesCounter;
/**
* @author Kuldeep.Mishra
*
*/
public interface DataKeeperService
{
void insertEmployee(Employee employee);
void insertData(DocumentInfo data);
Employee findEmployee(Object id);
Employee findEmployeeByName(String employeeName);
List findDocumentByEmployeeId(String employeeId);
List findDocumentByEmployeeName(String employeeName);
DocumentInfo findDocumentByDocumentId(int documentId);
void removeEmployee(Employee employee);
boolean authenticateEmployee(Employee employee, String password);
List findSubOrdinates(int managerId);
List findEmployeeByDateOfJoining(int noOfYears, String company);
void incrementCounter(SubordinatesCounter counter);
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperServiceImpl.java
================================================
package com.impetus.kundera.datakeeper.service;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.PersistenceException;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.datakeeper.dao.DataKeeperDao;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.entities.SubordinatesCounter;
/**
* @author Kuldeep.Mishra
*
*/
public class DataKeeperServiceImpl implements DataKeeperService
{
/**
* logger used for logging statement.
*/
private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);
private DataKeeperDao dao;
public DataKeeperServiceImpl()
{
}
public DataKeeperDao getDao()
{
return dao;
}
public void setDao(DataKeeperDao dao)
{
this.dao = dao;
}
@Override
public void insertEmployee(Employee employee)
{
employee.setPassword(encriptPassword(employee.getPassword()));
dao.insert(employee);
log.info("Employee {} information successfully inserted.", employee.getEmployeeName());
if (employee.getManager() != null)
{
SubordinatesCounter counter = new SubordinatesCounter();
counter.setNoOfSubordinates(1);
counter.setEmployeeId(employee.getManager().getEmployeeId());
dao.insert(counter);
log.info("Incremented no of subordinates for manager {}, successfully.", employee.getManager()
.getEmployeeName());
}
}
@Override
public Employee findEmployeeByName(String employeeName)
{
Employee employee = null;
String query = "Select e from " + Employee.class.getSimpleName() + " e where e.employeeName = " + employeeName;
List employees = (List) dao.findByQuery(query);
if (!employees.isEmpty() && employees.get(0) != null)
{
employee = employees.get(0);
}
return employee;
}
@Override
public List findSubOrdinates(int managerId)
{
Employee manager = dao.findById(Employee.class, managerId);
List subOrdinates = manager != null ? manager.getSubordinates() : new ArrayList();
return subOrdinates;
}
@Override
public void insertData(DocumentInfo data)
{
dao.insert(data);
log.info("Data uploaded by employee {} successfully inserted.", data.getOwnerName());
}
@Override
public Employee findEmployee(Object employeeId)
{
log.info("Finding employee by id {} .", employeeId);
return dao.findById(Employee.class, employeeId);
}
@Override
public List findDocumentByEmployeeId(String employeeId)
{
List documents = new ArrayList();
try
{
Integer.parseInt(employeeId);
documents = findDocumentByEmployeeId(Integer.parseInt(employeeId));
}
catch (NumberFormatException nfex)
{
log.warn("{} not a valid employee id.", employeeId);
}
return documents;
}
public List findDocumentByEmployeeId(int employeeId)
{
List documents = new ArrayList();
log.info("Finding document by employee id {} .", employeeId);
String query = "Select d from " + DocumentInfo.class.getSimpleName() + " d where d.ownerId = " + employeeId;
documents = (List) dao.findByQuery(query);
for (DocumentInfo documentInfo : documents)
{
StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),
"application/pdf");
documentInfo.addFile(file);
}
return documents;
}
@Override
public List findDocumentByEmployeeName(String employeeName)
{
List documents = new ArrayList();
log.info("Finding document by employee name {} .", employeeName);
String query = "Select d from " + DocumentInfo.class.getSimpleName() + " d where d.ownerName = "
+ employeeName;
documents = (List) dao.findByQuery(query);
for (DocumentInfo documentInfo : documents)
{
StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),
"application/pdf");
documentInfo.addFile(file);
}
return documents;
}
@Override
public void removeEmployee(Employee employee)
{
dao.remove(employee);
List documents = findDocumentByEmployeeId(employee.getEmployeeId());
for (DocumentInfo document : documents)
{
if (document != null)
{
dao.remove(document);
}
}
log.info("Employee successfully removed");
}
@Override
public boolean authenticateEmployee(Employee employee, String password)
{
boolean success = false;
if (employee != null && (employee.getPassword().equals(encriptPassword(password))))
{
log.info("Employee {} successfully authenticated.", employee.getEmployeeName());
success = true;
}
else
{
log.info("Employee not authenticated, caused by either wrong userName or wrong password.");
}
return success;
}
/**
* encriptPassword method used for encrypting password.
*
* @param password
* the password
* @return the string
*/
public String encriptPassword(String password)
{
String newpassword = null;
byte[] defaultBytes = password.getBytes();
try
{
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(defaultBytes);
byte messageDigest[] = algorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
{
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
}
newpassword = hexString.toString();
}
catch (NoSuchAlgorithmException e)
{
log.error("Error while encripting password {}, caused by : .", password, e);
throw new PersistenceException(e);
}
return newpassword;
}
@Override
public DocumentInfo findDocumentByDocumentId(int documentId)
{
log.info("Finding document by id.");
DocumentInfo document = dao.findById(DocumentInfo.class, documentId);
return document;
}
@Override
public List findEmployeeByDateOfJoining(final int noOfYears, final String company)
{
long currentTimeStamp = System.currentTimeMillis();
long newTimeStamp = currentTimeStamp - (long) noOfYears * 365 * 24 * 60 * 60 * 1000;
String query = "Select e from " + Employee.class.getSimpleName() + " e where e.company = " + company
+ " and e.timestamp <= :timestamp";
List subOrdinates = (List) dao.findByQuery(query, "timestamp", newTimeStamp);
return subOrdinates;
}
@Override
public void incrementCounter(SubordinatesCounter counter)
{
dao.insert(counter);
}
private StreamedContent toStreamedContent(byte[] bytes, String fileName, String contentType)
{
InputStream is = new ByteArrayInputStream(bytes);
StreamedContent file = new DefaultStreamedContent(is, contentType, fileName);
return file;
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataFormat.java
================================================
package com.impetus.kundera.datakeeper.utils;
/**
* @author Kuldeep.Mishra
*
*/
public enum DataFormat
{
XLS, XLSX, PDF, DOC, DOCX, AVI;
/**
* If provided protocol is within allowed protocol.
*
* @param protocol
* protocol
* @return true, if it is in allowed protocol.
*/
public static boolean isValidFormat(String format)
{
try
{
DataFormat.valueOf(format.toUpperCase());
return true;
}
catch (IllegalArgumentException iex)
{
return false;
}
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperConstants.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.datakeeper.utils;
/**
*
* @author amresh.singh
*/
public class DataKeeperConstants
{
public static final String OUTCOME_LOGIN_FAILED = "loginFailed";
public static final String OUTCOME_LOGIN_SUCCESSFUL = "loginSuccessful";
public static final String OUTCOME_SIGNUP_SUCCESSFUL = "signUpSuccessful";
public static final String OUTCOME_LOGOFF_SUCCESSFUL = "logOfSuccessful";
public static final String OUTCOME_TIMELINE = "timeline";
public static final String PERSISTENCE_UNIT = "twitample_cassandra";
public static final String EMPLOYEE_ID = "employeeId";
public static final String EMPLOYEE = "employee";
public static final String EMPLOYEE_NAME = "employeeName";
public static final String TWEET_DEVICE_WEB = "Web";
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperUtils.java
================================================
package com.impetus.kundera.datakeeper.utils;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
public class DataKeeperUtils
{
public static DataKeeperService getService()
{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
DataKeeperService datakeeper = (DataKeeperService) session.getAttribute("datakeeper");
if (datakeeper == null)
{
BeanFactory beanfactory = new ClassPathXmlApplicationContext("appContext.xml");
datakeeper = (DataKeeperService) beanfactory.getBean("datakeeper");
session.setAttribute("datakeeper", datakeeper);
}
return datakeeper;
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/FacesUtils.java
================================================
package com.impetus.kundera.datakeeper.utils;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* The Class FacesUtils has method for getting session variables and request
* variables.
*/
public class FacesUtils
{
/**
* getSession method used for getting session variable.
*
* @return the session
*/
public static HttpSession getSession()
{
return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
/**
* getRequest method used for getting request variable.
*
* @return the request
*/
public static HttpServletRequest getRequest()
{
return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
}
}
================================================
FILE: examples/container/jboss/data-keeper/src/main/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.datakeeper.entities.DocumentInfo
com.impetus.kundera.datakeeper.entities.Employee
com.impetus.kundera.datakeeper.entities.SubordinatesCounter
true
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.datakeeper.entities.DocumentInfo
true
com.impetus.kundera.KunderaPersistence
================================================
FILE: examples/container/jboss/data-keeper/src/main/resources/appContext.xml
================================================
META-INF/persistence.xml
org.apache.naming.java.javaURLContextFactory
org.apache.naming
================================================
FILE: examples/container/jboss/data-keeper/src/main/resources/kunderaCounter.xml
================================================
cassandra
datakeeper
================================================
FILE: examples/container/jboss/data-keeper/src/main/resources/log4j.properties
================================================
log4j.rootLogger=INFO, DRFA, CONSOLE
### direct log messages to stdout ###
log4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DRFA.File=${user.home}/kundera-benchmark.log
# Rollover at midnight
log4j.appender.DRFA.DatePattern=.yyyy-MM-dd
log4j.appender.DRFA.layout=org.apache.log4j.PatternLayout
# Pattern format: Date LogLevel LoggerName LogMessage
log4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/WEB-INF/faces-config.xml
================================================
/xhtml/login/login.xhtml
loginSuccessful
/xhtml/home/timeline.xhtml
loginFailed
/xhtml/login/login.xhtml
/xhtml/register/signUp.xhtml
signUpSuccessful
/xhtml/login/login.xhtml
/xhtml/register/signUp.xhtml
timeline
/xhtml/home/timeline.xhtml
/xhtml/home/timeline.xhtml
foundEmployess
/xhtml/home/showSubordinatesInfo.xhtml
/xhtml/home/showSubordinatesInfo.xhtml
foundEmployess
/xhtml/home/showSubordinatesInfo.xhtml
logOfSuccessful
/xhtml/login/login.xhtml
Account successfully deleted
/xhtml/login/login.xhtml
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/WEB-INF/web.xml
================================================
DataKeeper application
javax.faces.STATE_SAVING_METHOD
server
javax.faces.CONFIG_FILES
/WEB-INF/faces-config.xml
com.sun.faces.config.ConfigureListener
Faces Servlet
javax.faces.webapp.FacesServlet
1
Faces Servlet
*.jsf
xhtml/login/login.jsf
PrimeFaces FileUpload Filter
org.primefaces.webapp.filter.FileUploadFilter
thresholdSize
512000
uploadDirectory
C:\etc
PrimeFaces FileUpload Filter
Faces Servlet
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/appContext.xml
================================================
META-INF/persistence.xml
org.apache.naming.java.javaURLContextFactory
org.apache.naming
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/index.jsp
================================================
Hello World!
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/common/header.xhtml
================================================
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/common/leftPane.xhtml
================================================
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/common/loggedInHeader.xhtml
================================================
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfo.xhtml
================================================
DataKeeper :: Employees Information
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfoTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/timeline.xhtml
================================================
DataKeeper :: Home
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/timelineTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/login/login.xhtml
================================================
Kwitter :: Login
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/login/loginTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/register/signUp.xhtml
================================================
Kwitter :: SignUp
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/register/signUpTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/settings/settings.xhtml
================================================
Kwitter :: Settings
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/settings/settingsTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/upload/uploadDocument.xhtml
================================================
DataKeeper :: Upload
================================================
FILE: examples/container/jboss/data-keeper/src/main/webapp/xhtml/upload/uploadDocumentTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/jboss/pom.xml
================================================
4.0.0
com.impetus.kundera.examples
container
3.3-SNAPSHOT
com.impetus.kundera.examples
jboss
3.3-SNAPSHOT
pom
jboss-app
https://github.com/impetus-opensource/Kundera
all
true
data-keeper
================================================
FILE: examples/container/pom.xml
================================================
4.0.0
com.impetus.kundera
examples
3.3-SNAPSHOT
com.impetus.kundera.examples
container
3.3-SNAPSHOT
pom
container
https://github.com/impetus-opensource/Kundera
The Apache Software License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0.txt
repo
scm:git:git@github.com:impetus-opensource/Kundera.git
scm:git:git@github.com:impetus-opensource/Kundera.git
git@github.com:impetus-opensource/Kundera.git
vivek.mishra
Vivek Mishra
vivek.mishra@yahoo.com
amresh.singh
Amresh Kumar Singh
amresh1002@gmail.com
Kuldeep.mishra
Kuldeep Kumar Mishra
kuld.cs.mishra@gmail.com
UTF-8
UTF-8
jacoco
reuseReports
java
clover
Clover maven repo
http://mirrors.ibiblio.org/pub/mirrors/maven
true
true
kundera-missing
Kundera Public Missing Resources Repository
http://kundera.googlecode.com/svn/maven2/maven-missing-resources
true
true
riptano
riptano
http://mvn.riptano.com/content/repositories/public
maven.scale7.org
Scale7 Maven Repo
https://github.com/s7/mvnrepo/raw/master
true
all
true
jboss
tomcat-glassfish
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/pom.xml
================================================
4.0.0
com.impetus.kundera.examples
tomcat-glassfish
3.3-SNAPSHOT
com.impetus.kundera.examples
data-keeper
war
1.0-SNAPSHOT
data-keeper
http://maven.apache.org
UTF-8
3.0.5.RELEASE
3.3-SNAPSHOT
junit
junit
4.8.2
test
com.impetus.kundera.core
kundera-core
${kundera.version}
com.impetus.kundera.client
kundera-cassandra
${kundera.version}
com.impetus.kundera.client
kundera-mongo
${kundera.version}
javax.servlet
javax.servlet-api
3.0.1
provided
com.sun.faces
jsf-api
2.1.10
com.sun.faces
jsf-impl
2.1.10
jstl
jstl
1.2
org.primefaces
primefaces
3.3.1
commons-fileupload
commons-fileupload
1.3
commons-io
commons-io
2.4
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-orm
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-test
${spring.version}
data-keeper
maven-compiler-plugin
1.7
1.7
true
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentDownloadBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "documentDownloadBean")
@RequestScoped
public class DocumentDownloadBean
{
private int documentId;
public int getDocumentId()
{
return documentId;
}
public void setDocumentId(int documentId)
{
this.documentId = documentId;
}
/**
* Download file used for downloading photo.
*
* @param photoPath
* the photo path
*/
public void download()
{
DataKeeperService service = DataKeeperUtils.getService();
setDocumentId(Integer.parseInt(FacesUtils.getRequest().getParameter("documentId")));
DocumentInfo document = service.findDocumentByDocumentId(getDocumentId());
final HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
ServletOutputStream out = null;
try
{
out = response.getOutputStream();
out.write(document.getData(), 0, 4096);
}
catch (IOException e)
{
}
finally
{
if (out != null)
{
try
{
out.flush();
out.close();
}
catch (IOException e)
{
}
}
}
FacesContext.getCurrentInstance().responseComplete();
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentSearchBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
@ManagedBean(name = "documentSearchBean")
@RequestScoped
public class DocumentSearchBean
{
private String searchText;
private int searchBy;
private List documents;
public String getSearchText()
{
return searchText;
}
public void setSearchText(String searchText)
{
this.searchText = searchText;
}
public int getSearchBy()
{
return searchBy;
}
public void setSearchBy(int searchBy)
{
this.searchBy = searchBy;
}
public List getDocuments()
{
return documents;
}
public void setDocuments(List documents)
{
this.documents = documents;
}
public List search()
{
documents = new ArrayList();
DataKeeperService service = DataKeeperUtils.getService();
switch (SearchType.getSearchType(searchBy))
{
case ID:
documents = service.findDocumentByEmployeeId(getSearchText());
break;
case NAME:
documents = service.findDocumentByEmployeeName(getSearchText());
break;
}
return documents;
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentUploadBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "documentUploadBean")
@RequestScoped
public class DocumentUploadBean
{
public DocumentUploadBean()
{
}
public String handleFileUpload(FileUploadEvent event)
{
HttpSession session = FacesUtils.getSession();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
DataKeeperService service = DataKeeperUtils.getService();
UploadedFile file = event.getFile();
if (file != null)
{
DocumentInfo dataInfo = new DocumentInfo();
dataInfo.setData(file.getContents());
dataInfo.setDocumentName(file.getFileName());
dataInfo.setSize(file.getSize());
dataInfo.setOwnerName(employee.getEmployeeName());
dataInfo.setOwnerId(employee.getEmployeeId());
dataInfo.setUplodedDate(new Date());
service.insertData(dataInfo);
FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "successfully uploaded";
}
return "uploading fail";
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/EmployeeSearchBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.servlet.http.HttpSession;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "subordinateSearchBean")
@RequestScoped
public class EmployeeSearchBean
{
private List subordinates = new ArrayList();
private int managerId;
private int noOfYears;
private String searchText;
private int searchBy;
public String getSearchText()
{
return searchText;
}
public void setSearchText(String searchText)
{
this.searchText = searchText;
}
public int getSearchBy()
{
return searchBy;
}
public void setSearchBy(int searchBy)
{
this.searchBy = searchBy;
}
/**
* @return the managerName
*/
public int getManagerId()
{
return managerId;
}
/**
* @param managerName
* the managerName to set
*/
public void setManagerId(int managerId)
{
this.managerId = managerId;
}
public int getNoOfYears()
{
return noOfYears;
}
public void setNoOfYears(int noOfYears)
{
this.noOfYears = noOfYears;
}
public List getSubordinates()
{
return subordinates;
}
public void setSubordinates(List subordinates)
{
this.subordinates = subordinates;
}
public String searchSubordinates()
{
DataKeeperService service = DataKeeperUtils.getService();
setManagerId(Integer.parseInt(FacesUtils.getRequest().getParameter("managerId")));
List subordinates = service.findSubOrdinates(getManagerId());
if (subordinates != null)
{
this.subordinates = subordinates;
}
return "foundEmployess";
}
public String searchEmployee()
{
DataKeeperService service = DataKeeperUtils.getService();
Employee employee = null;
switch (SearchType.getSearchType(searchBy))
{
case ID:
employee = service.findEmployee(Integer.parseInt(getSearchText()));
break;
case NAME:
employee = service.findEmployeeByName(getSearchText());
break;
}
if (employee != null)
{
List employees = new ArrayList();
employees.add(employee);
this.subordinates = employees;
}
return "foundEmployess";
}
public String searchEmployeeByYearOfComplition()
{
DataKeeperService service = DataKeeperUtils.getService();
HttpSession session = FacesUtils.getSession();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
List employees = service.findEmployeeByDateOfJoining(getNoOfYears(), employee.getCompany());
if (employees != null)
{
this.subordinates = employees;
}
return "foundEmployess";
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/IncrementCounterBean.java
================================================
package com.impetus.kundera.datakeeper.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.servlet.http.HttpSession;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.entities.SubordinatesCounter;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
@ManagedBean(name = "incrementCounterBean")
@RequestScoped
public class IncrementCounterBean
{
private SubordinatesCounter counter = new SubordinatesCounter();
public IncrementCounterBean()
{
}
public SubordinatesCounter getCounter()
{
return counter;
}
public void setCounter(SubordinatesCounter counter)
{
this.counter = counter;
}
public String incrementCounter()
{
DataKeeperService service = DataKeeperUtils.getService();
HttpSession session = FacesUtils.getSession();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
counter.setEmployeeId(employee.getEmployeeId());
service.incrementCounter(counter);
return "success";
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/LoginBean.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.datakeeper.beans;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperConstants;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
import com.impetus.kundera.datakeeper.utils.FacesUtils;
/**
*
*
* @author amresh.singh
*/
@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean
{
private Employee employee = new Employee();
public LoginBean()
{
}
public Employee getEmployee()
{
return employee;
}
public void setEmployee(Employee employee)
{
this.employee = employee;
}
public String logOff()
{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You have successfully Logged off"));
session.invalidate();
return DataKeeperConstants.OUTCOME_LOGOFF_SUCCESSFUL;
}
public String deleteAccount()
{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
DataKeeperService service = DataKeeperUtils.getService();
Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);
service.removeEmployee(employee);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Account successfully deleted"));
session.invalidate();
return "Account successfully deleted";
}
public String authenticate()
{
String outcome = null;
// Validates Parameters
if (StringUtils.isBlank(employee.getEmployeeName()))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter your user name"));
outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
}
if (StringUtils.isBlank(employee.getPassword()))
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter password"));
outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
}
if (StringUtils.isNotBlank(outcome))
{
return outcome;
}
else
{
DataKeeperService service = DataKeeperUtils.getService();
Employee foundEmployee = service.findEmployeeByName(employee.getEmployeeName());
boolean success = service.authenticateEmployee(foundEmployee, employee.getPassword());
if (!success)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Incorrect User Name/Password"));
outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
}
else
{
outcome = DataKeeperConstants.OUTCOME_LOGIN_SUCCESSFUL;
HttpSession session = FacesUtils.getSession();
session.setAttribute(DataKeeperConstants.EMPLOYEE, foundEmployee);
}
return outcome;
}
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/RegisterBean.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.datakeeper.beans;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FlowEvent;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
import com.impetus.kundera.datakeeper.utils.DataKeeperUtils;
/**
*
*
* @author Kuldeep.Mishra
*/
@ManagedBean(name = "registerBean")
@RequestScoped
public class RegisterBean
{
private Employee employee = new Employee();
private int managerId;
public RegisterBean()
{
}
public Employee getEmployee()
{
return employee;
}
public void setEmployee(Employee employee)
{
this.employee = employee;
}
public int getManagerId()
{
return managerId;
}
public void setManagerId(int managerId)
{
this.managerId = managerId;
}
public String onFlowProcess(FlowEvent event)
{
return event.getNewStep();
}
public String save()
{
DataKeeperService service = DataKeeperUtils.getService();
Employee manager = service.findEmployee(managerId);
employee.setManager(manager);
employee.setTimestamp(employee.getJoiningDate().getTime());
service.insertEmployee(employee);
FacesMessage msg = new FacesMessage("SignUp Successful! Welcome, " + employee.getEmployeeName());
FacesContext.getCurrentInstance().addMessage(null, msg);
return "signUpSuccessful";
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/SearchType.java
================================================
/**
*
*/
package com.impetus.kundera.datakeeper.beans;
/**
* @author Kuldeep.Mishra
*
*/
enum SearchType
{
ID, NAME;
static SearchType getSearchType(int searchBy)
{
if (searchBy == 1)
{
return ID;
}
else if (searchBy == 0)
{
return NAME;
}
return null;
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDao.java
================================================
package com.impetus.kundera.datakeeper.dao;
import java.util.List;
import javax.persistence.EntityManager;
/**
* @author Kuldeep.Mishra
*
*/
public interface DataKeeperDao
{
EntityManager getEntityManager();
void closeEntityManager();
void clearEntityManager();
void shutDown();
void insert(Object entity);
void merge(Object entity);
void remove(Object entity);
T findById(Class entityClazz, Object id);
List> findByQuery(String Query);
List> findByQuery(String queryString, String paramater, Object parameterValue);
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDaoImpl.java
================================================
package com.impetus.kundera.datakeeper.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl;
/**
* @author Kuldeep.Mishra
*
*/
// @Transactional(propagation = Propagation.REQUIRED)
public class DataKeeperDaoImpl implements DataKeeperDao
{
/**
* logger used for logging statement.
*/
private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);
@PersistenceContext(unitName = "cassandra-pu,mongo-pu", type = PersistenceContextType.EXTENDED)
private EntityManager em;
public DataKeeperDaoImpl()
{
}
@Override
public void insert(Object entity)
{
em.persist(entity);
em.clear();
}
@Override
public void merge(Object entity)
{
em.merge(entity);
em.clear();
}
@Override
public void remove(Object entity)
{
em.remove(entity);
em.clear();
}
@Override
public T findById(Class entityClazz, Object id)
{
T results = em.find(entityClazz, id);
return results;
}
@Override
public List> findByQuery(String queryString)
{
log.info(queryString);
Query query = em.createQuery(queryString);
List> resultList = query.getResultList();
return resultList;
}
@Override
public List> findByQuery(String queryString, String paramater, Object parameterValue)
{
Query query = em.createQuery(queryString);
query.setParameter(paramater, parameterValue);
log.info(queryString);
List> resultList = query.getResultList();
return resultList;
}
@Override
public EntityManager getEntityManager()
{
return em;
}
@Override
public void closeEntityManager()
{
if (em != null)
{
em.close();
}
}
@Override
public void clearEntityManager()
{
if (em != null)
{
em.clear();
}
}
@Override
public void shutDown()
{
if (em != null)
{
em.close();
}
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/DocumentInfo.java
================================================
package com.impetus.kundera.datakeeper.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.primefaces.model.StreamedContent;
import com.impetus.kundera.datakeeper.utils.DataFormat;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* @author Kuldeep.Mishra
*
*/
@Entity
@Table(name = "DOCUMENT", schema = "datakeeper@mongo-pu")
@IndexCollection(columns = { @Index(name = "ownerName"), @Index(name = "ownerId"), @Index(name = "documentName") })
public class DocumentInfo
{
@Id
@Column(name = "DOCUMENT_ID")
@GeneratedValue()
private String dataId;
@Column(name = "EMPLOYEE_NAME")
private String ownerName;
@Column(name = "EMPLOYEE_ID")
private int ownerId;
@Column(name = "UPLOADED_DATE")
private Date uplodedDate;
@Column(name = "DOCUMENT_FORMAT")
private DataFormat dataFormat;
@Column(name = "DOCUMENT_NAME")
private String documentName;
@Column(name = "DATA")
private byte[] data;
private StreamedContent file;
@Column(name = "SIZE")
private long size;
/**
* @return the dataId
*/
public String getDataId()
{
return dataId;
}
/**
* @param dataId
* the dataId to set
*/
public void setDataId(String dataId)
{
this.dataId = dataId;
}
/**
* @return the ownerName
*/
public String getOwnerName()
{
return ownerName;
}
/**
* @param ownerName
* the ownerName to set
*/
public void setOwnerName(String ownerName)
{
this.ownerName = ownerName;
}
/**
* @return the ownerId
*/
public int getOwnerId()
{
return ownerId;
}
/**
* @param ownerId
* the ownerId to set
*/
public void setOwnerId(int ownerId)
{
this.ownerId = ownerId;
}
/**
* @return the uplodedDate
*/
public Date getUplodedDate()
{
return uplodedDate;
}
/**
* @param uplodedDate
* the uplodedDate to set
*/
public void setUplodedDate(Date uplodedDate)
{
this.uplodedDate = uplodedDate;
}
/**
* @return the dataFormat
*/
public DataFormat getDataFormat()
{
return dataFormat;
}
/**
* @param dataFormat
* the dataFormat to set
*/
public void setDataFormat(DataFormat dataFormat)
{
this.dataFormat = dataFormat;
}
public byte[] getData()
{
return data;
}
public void setData(byte[] data)
{
this.data = data;
}
public String getDocumentName()
{
return documentName;
}
public void setDocumentName(String documentName)
{
this.documentName = documentName;
}
public long getSize()
{
return size;
}
public void setSize(long size)
{
this.size = size;
}
public StreamedContent getFile()
{
return file;
}
public void addFile(StreamedContent file)
{
this.file = file;
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/Employee.java
================================================
package com.impetus.kundera.datakeeper.entities;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* @author Kuldeep.Mishra
*
*/
@Entity
@Table(name = "EMPLOYEE", schema = "datakeeper@cassandra-pu")
@IndexCollection(columns = { @Index(name = "employeeName"), @Index(name = "designation"), @Index(name = "experience"),
@Index(name = "joiningDate"), @Index(name = "currentProject"), @Index(name = "timestamp"),
@Index(name = "company") })
public class Employee
{
@Id
@Column(name = "EMPLOYEE_ID")
@GeneratedValue(strategy = GenerationType.TABLE)
private int employeeId;
@Column(name = "PASSWORD")
private String password;
@Column(name = "EMPLOYEE_NAME")
private String employeeName;
@Column(name = "EXPERIENCE")
private int experience;
@Column(name = "JOINING_DATE")
private Date joiningDate;
@Column(name = "DESIGNATION")
private String designation;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "MANAGER_ID")
private Employee manager;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "manager")
private List subordinates;
@Column(name = "PROJECT")
private String currentProject;
@Column(name = "COMPANY")
private String company;
@Column(name = "JOINING_TIMESTAMP")
private long timestamp;
public int getEmployeeId()
{
return employeeId;
}
public void setEmployeeId(int employeeId)
{
this.employeeId = employeeId;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmployeeName()
{
return employeeName;
}
public void setEmployeeName(String employeeName)
{
this.employeeName = employeeName;
}
public int getExperience()
{
return experience;
}
public void setExperience(int experience)
{
this.experience = experience;
}
public Date getJoiningDate()
{
return joiningDate;
}
public void setJoiningDate(Date joiningDate)
{
this.joiningDate = joiningDate;
}
public String getDesignation()
{
return designation;
}
public void setDesignation(String designation)
{
this.designation = designation;
}
public Employee getManager()
{
return manager;
}
public void setManager(Employee manager)
{
this.manager = manager;
}
public String getCurrentProject()
{
return currentProject;
}
public void setCurrentProject(String currentProject)
{
this.currentProject = currentProject;
}
public List getSubordinates()
{
return subordinates;
}
public void setSubordinates(List subordinates)
{
this.subordinates = subordinates;
}
public long getTimestamp()
{
return timestamp;
}
public void setTimestamp(long timestamp)
{
this.timestamp = timestamp;
}
public String getCompany()
{
return company;
}
public void setCompany(String company)
{
this.company = company;
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/SubordinatesCounter.java
================================================
package com.impetus.kundera.datakeeper.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "SUBORDINATES_COUNTER", schema = "datakeeper@cassandra-pu")
public class SubordinatesCounter
{
@Id
@Column(name = "EMPLOYEE_ID")
private int employeeId;
@Column(name = "SUBORDINATES_COUNTER")
private int noOfSubordinates;
public int getEmployeeId()
{
return employeeId;
}
public void setEmployeeId(int employeeId)
{
this.employeeId = employeeId;
}
public int getNoOfSubordinates()
{
return noOfSubordinates;
}
public void setNoOfSubordinates(int noOfSubordinates)
{
this.noOfSubordinates = noOfSubordinates;
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperService.java
================================================
package com.impetus.kundera.datakeeper.service;
import java.util.List;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.entities.SubordinatesCounter;
/**
* @author Kuldeep.Mishra
*
*/
public interface DataKeeperService
{
void insertEmployee(Employee employee);
void insertData(DocumentInfo data);
Employee findEmployee(Object id);
Employee findEmployeeByName(String employeeName);
List findDocumentByEmployeeId(String employeeId);
List findDocumentByEmployeeName(String employeeName);
DocumentInfo findDocumentByDocumentId(int documentId);
void removeEmployee(Employee employee);
boolean authenticateEmployee(Employee employee, String password);
List findSubOrdinates(int managerId);
List findEmployeeByDateOfJoining(int noOfYears, String company);
void incrementCounter(SubordinatesCounter counter);
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperServiceImpl.java
================================================
package com.impetus.kundera.datakeeper.service;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.PersistenceException;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.datakeeper.dao.DataKeeperDao;
import com.impetus.kundera.datakeeper.entities.DocumentInfo;
import com.impetus.kundera.datakeeper.entities.Employee;
import com.impetus.kundera.datakeeper.entities.SubordinatesCounter;
/**
* @author Kuldeep.Mishra
*
*/
public class DataKeeperServiceImpl implements DataKeeperService
{
/**
* logger used for logging statement.
*/
private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);
private DataKeeperDao dao;
public DataKeeperServiceImpl()
{
}
public DataKeeperDao getDao()
{
return dao;
}
public void setDao(DataKeeperDao dao)
{
this.dao = dao;
}
@Override
public void insertEmployee(Employee employee)
{
employee.setPassword(encriptPassword(employee.getPassword()));
dao.insert(employee);
log.info("Employee {} information successfully inserted.", employee.getEmployeeName());
if (employee.getManager() != null)
{
SubordinatesCounter counter = new SubordinatesCounter();
counter.setNoOfSubordinates(1);
counter.setEmployeeId(employee.getManager().getEmployeeId());
dao.insert(counter);
log.info("Incremented no of subordinates for manager {}, successfully.", employee.getManager()
.getEmployeeName());
}
}
@Override
public Employee findEmployeeByName(String employeeName)
{
Employee employee = null;
String query = "Select e from " + Employee.class.getSimpleName() + " e where e.employeeName = " + employeeName;
List employees = (List) dao.findByQuery(query);
if (!employees.isEmpty() && employees.get(0) != null)
{
employee = employees.get(0);
}
return employee;
}
@Override
public List findSubOrdinates(int managerId)
{
Employee manager = dao.findById(Employee.class, managerId);
List subOrdinates = manager != null ? manager.getSubordinates() : new ArrayList();
return subOrdinates;
}
@Override
public void insertData(DocumentInfo data)
{
dao.insert(data);
log.info("Data uploaded by employee {} successfully inserted.", data.getOwnerName());
}
@Override
public Employee findEmployee(Object employeeId)
{
log.info("Finding employee by id {} .", employeeId);
return dao.findById(Employee.class, employeeId);
}
@Override
public List findDocumentByEmployeeId(String employeeId)
{
List documents = new ArrayList();
try
{
Integer.parseInt(employeeId);
documents = findDocumentByEmployeeId(Integer.parseInt(employeeId));
}
catch (NumberFormatException nfex)
{
log.warn("{} not a valid employee id.", employeeId);
}
return documents;
}
public List findDocumentByEmployeeId(int employeeId)
{
List documents = new ArrayList();
log.info("Finding document by employee id {} .", employeeId);
String query = "Select d from " + DocumentInfo.class.getSimpleName() + " d where d.ownerId = " + employeeId;
documents = (List) dao.findByQuery(query);
for (DocumentInfo documentInfo : documents)
{
StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),
"application/pdf");
documentInfo.addFile(file);
}
return documents;
}
@Override
public List findDocumentByEmployeeName(String employeeName)
{
List documents = new ArrayList();
log.info("Finding document by employee name {} .", employeeName);
String query = "Select d from " + DocumentInfo.class.getSimpleName() + " d where d.ownerName = "
+ employeeName;
documents = (List) dao.findByQuery(query);
for (DocumentInfo documentInfo : documents)
{
StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),
"application/pdf");
documentInfo.addFile(file);
}
return documents;
}
@Override
public void removeEmployee(Employee employee)
{
dao.remove(employee);
List documents = findDocumentByEmployeeId(employee.getEmployeeId());
for (DocumentInfo document : documents)
{
if (document != null)
{
dao.remove(document);
}
}
log.info("Employee successfully removed");
}
@Override
public boolean authenticateEmployee(Employee employee, String password)
{
boolean success = false;
if (employee != null && (employee.getPassword().equals(encriptPassword(password))))
{
log.info("Employee {} successfully authenticated.", employee.getEmployeeName());
success = true;
}
else
{
log.info("Employee not authenticated, caused by either wrong userName or wrong password.");
}
return success;
}
/**
* encriptPassword method used for encrypting password.
*
* @param password
* the password
* @return the string
*/
public String encriptPassword(String password)
{
String newpassword = null;
byte[] defaultBytes = password.getBytes();
try
{
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(defaultBytes);
byte messageDigest[] = algorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
{
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
}
newpassword = hexString.toString();
}
catch (NoSuchAlgorithmException e)
{
log.error("Error while encripting password {}, caused by : .", password, e);
throw new PersistenceException(e);
}
return newpassword;
}
@Override
public DocumentInfo findDocumentByDocumentId(int documentId)
{
log.info("Finding document by id.");
DocumentInfo document = dao.findById(DocumentInfo.class, documentId);
return document;
}
@Override
public List findEmployeeByDateOfJoining(final int noOfYears, final String company)
{
long currentTimeStamp = System.currentTimeMillis();
long newTimeStamp = currentTimeStamp - (long) noOfYears * 365 * 24 * 60 * 60 * 1000;
String query = "Select e from " + Employee.class.getSimpleName() + " e where e.company = " + company
+ " and e.timestamp <= :timestamp";
List subOrdinates = (List) dao.findByQuery(query, "timestamp", newTimeStamp);
return subOrdinates;
}
@Override
public void incrementCounter(SubordinatesCounter counter)
{
dao.insert(counter);
}
private StreamedContent toStreamedContent(byte[] bytes, String fileName, String contentType)
{
InputStream is = new ByteArrayInputStream(bytes);
StreamedContent file = new DefaultStreamedContent(is, contentType, fileName);
return file;
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataFormat.java
================================================
package com.impetus.kundera.datakeeper.utils;
/**
* @author Kuldeep.Mishra
*
*/
public enum DataFormat
{
XLS, XLSX, PDF, DOC, DOCX, AVI;
/**
* If provided protocol is within allowed protocol.
*
* @param protocol
* protocol
* @return true, if it is in allowed protocol.
*/
public static boolean isValidFormat(String format)
{
try
{
DataFormat.valueOf(format.toUpperCase());
return true;
}
catch (IllegalArgumentException iex)
{
return false;
}
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperConstants.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera.datakeeper.utils;
/**
*
* @author amresh.singh
*/
public class DataKeeperConstants
{
public static final String OUTCOME_LOGIN_FAILED = "loginFailed";
public static final String OUTCOME_LOGIN_SUCCESSFUL = "loginSuccessful";
public static final String OUTCOME_SIGNUP_SUCCESSFUL = "signUpSuccessful";
public static final String OUTCOME_LOGOFF_SUCCESSFUL = "logOfSuccessful";
public static final String OUTCOME_TIMELINE = "timeline";
public static final String PERSISTENCE_UNIT = "twitample_cassandra";
public static final String EMPLOYEE_ID = "employeeId";
public static final String EMPLOYEE = "employee";
public static final String EMPLOYEE_NAME = "employeeName";
public static final String TWEET_DEVICE_WEB = "Web";
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperUtils.java
================================================
package com.impetus.kundera.datakeeper.utils;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.impetus.kundera.datakeeper.service.DataKeeperService;
public class DataKeeperUtils
{
public static DataKeeperService getService()
{
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
DataKeeperService datakeeper = (DataKeeperService) session.getAttribute("datakeeper");
if (datakeeper == null)
{
BeanFactory beanfactory = new ClassPathXmlApplicationContext("appContext.xml");
datakeeper = (DataKeeperService) beanfactory.getBean("datakeeper");
session.setAttribute("datakeeper", datakeeper);
}
return datakeeper;
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/FacesUtils.java
================================================
package com.impetus.kundera.datakeeper.utils;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* The Class FacesUtils has method for getting session variables and request
* variables.
*/
public class FacesUtils
{
/**
* getSession method used for getting session variable.
*
* @return the session
*/
public static HttpSession getSession()
{
return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
/**
* getRequest method used for getting request variable.
*
* @return the request
*/
public static HttpServletRequest getRequest()
{
return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
}
}
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.datakeeper.entities.DocumentInfo
com.impetus.kundera.datakeeper.entities.Employee
com.impetus.kundera.datakeeper.entities.SubordinatesCounter
true
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.datakeeper.entities.DocumentInfo
true
com.impetus.kundera.KunderaPersistence
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/resources/appContext.xml
================================================
META-INF/persistence.xml
org.apache.naming.java.javaURLContextFactory
org.apache.naming
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/resources/kunderaCounter.xml
================================================
cassandra
datakeeper
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/resources/log4j.properties
================================================
log4j.rootLogger=INFO, DRFA, CONSOLE
### direct log messages to stdout ###
log4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DRFA.File=${user.home}/kundera-benchmark.log
# Rollover at midnight
log4j.appender.DRFA.DatePattern=.yyyy-MM-dd
log4j.appender.DRFA.layout=org.apache.log4j.PatternLayout
# Pattern format: Date LogLevel LoggerName LogMessage
log4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/WEB-INF/faces-config.xml
================================================
/xhtml/login/login.xhtml
loginSuccessful
/xhtml/home/timeline.xhtml
loginFailed
/xhtml/login/login.xhtml
/xhtml/register/signUp.xhtml
signUpSuccessful
/xhtml/login/login.xhtml
/xhtml/register/signUp.xhtml
timeline
/xhtml/home/timeline.xhtml
/xhtml/home/timeline.xhtml
foundEmployess
/xhtml/home/showSubordinatesInfo.xhtml
/xhtml/home/showSubordinatesInfo.xhtml
foundEmployess
/xhtml/home/showSubordinatesInfo.xhtml
logOfSuccessful
/xhtml/login/login.xhtml
Account successfully deleted
/xhtml/login/login.xhtml
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/WEB-INF/web.xml
================================================
DataKeeper application
javax.faces.STATE_SAVING_METHOD
server
javax.faces.CONFIG_FILES
/WEB-INF/faces-config.xml
com.sun.faces.config.ConfigureListener
Faces Servlet
javax.faces.webapp.FacesServlet
1
Faces Servlet
*.jsf
xhtml/login/login.jsf
PrimeFaces FileUpload Filter
org.primefaces.webapp.filter.FileUploadFilter
thresholdSize
512000
uploadDirectory
C:\etc
PrimeFaces FileUpload Filter
Faces Servlet
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/appContext.xml
================================================
META-INF/persistence.xml
org.apache.naming.java.javaURLContextFactory
org.apache.naming
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/index.jsp
================================================
Hello World!
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/common/header.xhtml
================================================
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/common/leftPane.xhtml
================================================
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/common/loggedInHeader.xhtml
================================================
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfo.xhtml
================================================
DataKeeper :: Employees Information
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfoTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/timeline.xhtml
================================================
DataKeeper :: Home
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/timelineTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/login/login.xhtml
================================================
Kwitter :: Login
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/login/loginTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/register/signUp.xhtml
================================================
Kwitter :: SignUp
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/register/signUpTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/settings/settings.xhtml
================================================
Kwitter :: Settings
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/settings/settingsTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/upload/uploadDocument.xhtml
================================================
DataKeeper :: Upload
================================================
FILE: examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/upload/uploadDocumentTemplate.xhtml
================================================
Default title
================================================
FILE: examples/container/tomcat-glassfish/pom.xml
================================================
4.0.0
com.impetus.kundera.examples
container
3.3-SNAPSHOT
com.impetus.kundera.examples
tomcat-glassfish
3.3-SNAPSHOT
pom
tomcat-glassfish
https://github.com/impetus-opensource/Kundera
all
true
data-keeper
================================================
FILE: examples/data-as-object-example/pom.xml
================================================
4.0.0
com.impetus
data-as-object-example
jar
1.0-SNAPSHOT
data-as-object-example
http://maven.apache.org
3.4-SNAPSHOT
com.impetus.kundera.client
data-as-object
${kundera-version}
com.impetus.kundera.client
kundera-cassandra
${kundera-version}
com.impetus.kundera.client
kundera-mongo
${kundera-version}
com.impetus.kundera.client
kundera-rdbms
${kundera-version}
com.impetus.kundera.client
kundera-kudu
${kundera-version}
maven-compiler-plugin
3.1
1.7
1.7
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/crud/CassandraCRUDTest.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.crud;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.kundera.dataasobject.entities.Employee;
import junit.framework.Assert;
/**
* The Class CassandraCRUDTest.
*/
public class CassandraCRUDTest
{
/**
* Sets the up before class.
*/
@BeforeClass
public static void SetUpBeforeClass()
{
Employee.bind("client-properties.json", Employee.class);
}
/**
* Test crud.
*/
@Test
public void testCRUD()
{
testInsert();
testUpdate();
testDelete();
}
/**
* Test insert.
*/
private void testInsert()
{
Employee emp = new Employee();
emp.setEmplyoeeId(101l);
emp.setName("karthik");
emp.setSalary(50000d);
emp.save();
Employee e = new Employee().find(101l);
Assert.assertEquals(Long.valueOf(101), e.getEmplyoeeId());
Assert.assertEquals("karthik", e.getName());
Assert.assertEquals(50000d, e.getSalary());
}
/**
* Test update.
*/
private void testUpdate()
{
Employee e = new Employee().find(101l);
e.setName("dev");
e.update();
Employee e1 = new Employee().find(101l);
Assert.assertEquals(Long.valueOf(101), e1.getEmplyoeeId());
Assert.assertEquals("dev", e1.getName());
Assert.assertEquals(50000d, e1.getSalary());
}
/**
* Test delete.
*/
private void testDelete()
{
Employee e = new Employee().find(101l);
e.delete();
Employee e1 = new Employee().find(101l);
Assert.assertNull(e1);
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
Employee.unbind();
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/crud/KuduCRUDTest.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.crud;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.kundera.dataasobject.entities.Customer;
import junit.framework.Assert;
/**
* The Class KuduCRUDTest.
*/
public class KuduCRUDTest
{
/**
* Sets the up before class.
*/
@BeforeClass
public static void SetUpBeforeClass()
{
Customer.bind("client-properties.json", Customer.class);
}
/**
* Test crud.
*/
@Test
public void testCRUD()
{
testInsert();
testUpdate();
testDelete();
}
/**
* Test insert.
*/
private void testInsert()
{
Customer customer = new Customer();
customer.setCustomerId(101);
customer.setName("dev");
customer.setLocation("Noida");
customer.save();
Customer c = new Customer().find(101);
Assert.assertEquals(101, c.getCustomerId());
Assert.assertEquals("dev", c.getName());
Assert.assertEquals("Noida", c.getLocation());
}
/**
* Test update.
*/
private void testUpdate()
{
Customer c = new Customer().find(101);
c.setName("karthik");
c.update();
Customer c1 = new Customer().find(101);
Assert.assertEquals(101, c1.getCustomerId());
Assert.assertEquals("karthik", c1.getName());
Assert.assertEquals("Noida", c1.getLocation());
}
/**
* Test delete.
*/
private void testDelete()
{
Customer c = new Customer().find(101);
c.delete();
Customer c1 = new Customer().find(101);
Assert.assertNull(c1);
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
Customer.unbind();
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Book.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.impetus.core.DefaultKunderaEntity;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* The Class Book.
*
*/
@Entity
@IndexCollection(columns = { @Index(name = "title"), @Index(name = "author"), @Index(name = "year"),
@Index(name = "pages") })
public class Book extends DefaultKunderaEntity
{
/** The book_id. */
@Id
@Column(name = "ID")
private Integer bookId;
/** The title. */
@Column(name = "TITLE")
private String title;
/** The author. */
@Column(name = "AUTHOR")
private String author;
/** The year. */
@Column(name = "YEAR")
private int year;
/** The pages. */
@Column(name = "PAGES")
private int pages;
/**
* Gets the book id.
*
* @return the book id
*/
public Integer getBookId()
{
return bookId;
}
/**
* Sets the book id.
*
* @param bookId
* the new book id
*/
public void setBookId(Integer bookId)
{
this.bookId = bookId;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle()
{
return title;
}
/**
* Sets the title.
*
* @param title
* the new title
*/
public void setTitle(String title)
{
this.title = title;
}
/**
* Gets the author.
*
* @return the author
*/
public String getAuthor()
{
return author;
}
/**
* Sets the author.
*
* @param author
* the new author
*/
public void setAuthor(String author)
{
this.author = author;
}
/**
* Gets the year.
*
* @return the year
*/
public int getYear()
{
return year;
}
/**
* Sets the year.
*
* @param year
* the new year
*/
public void setYear(int year)
{
this.year = year;
}
/**
* Gets the pages.
*
* @return the pages
*/
public int getPages()
{
return pages;
}
/**
* Sets the pages.
*
* @param pages
* the new pages
*/
public void setPages(int pages)
{
this.pages = pages;
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Customer.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.impetus.core.DefaultKunderaEntity;
/**
* The Class Customer.
*/
@Entity
public class Customer extends DefaultKunderaEntity
{
/** The customer id. */
@Id
private int customerId;
/** The name. */
private String name;
/** The location. */
private String location;
/**
* Gets the customer id.
*
* @return the customer id
*/
public int getCustomerId()
{
return customerId;
}
/**
* Sets the customer id.
*
* @param customerId
* the new customer id
*/
public void setCustomerId(int customerId)
{
this.customerId = customerId;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName()
{
return name;
}
/**
* Sets the name.
*
* @param name
* the new name
*/
public void setName(String name)
{
this.name = name;
}
/**
* Gets the location.
*
* @return the location
*/
public String getLocation()
{
return location;
}
/**
* Sets the location.
*
* @param location
* the new location
*/
public void setLocation(String location)
{
this.location = location;
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Department.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.impetus.core.DefaultKunderaEntity;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* The Class Department.
*/
@Entity
@IndexCollection(columns = { @Index(name = "employeeId") })
public class Department extends DefaultKunderaEntity
{
/** The dept id. */
@Id
private Long deptId;
/** The employee id. */
private Long employeeId;
/** The department name. */
private String departmentName;
/**
* Gets the dept id.
*
* @return the dept id
*/
public Long getDeptId()
{
return deptId;
}
/**
* Sets the dept id.
*
* @param deptId
* the new dept id
*/
public void setDeptId(Long deptId)
{
this.deptId = deptId;
}
/**
* Gets the employee id.
*
* @return the employee id
*/
public Long getEmployeeId()
{
return employeeId;
}
/**
* Sets the employee id.
*
* @param employeeId
* the new employee id
*/
public void setEmployeeId(Long employeeId)
{
this.employeeId = employeeId;
}
/**
* Gets the department name.
*
* @return the department name
*/
public String getDepartmentName()
{
return departmentName;
}
/**
* Sets the department name.
*
* @param departmentName
* the new department name
*/
public void setDepartmentName(String departmentName)
{
this.departmentName = departmentName;
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/DepartmentKudu.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.impetus.core.DefaultKunderaEntity;
/**
* The Class DepartmentKudu.
*/
@Entity
public class DepartmentKudu extends DefaultKunderaEntity
{
/** The dept id. */
@Id
private Long deptId;
/** The employee id. */
private Long employeeId;
/** The department name. */
private String departmentName;
/**
* Gets the dept id.
*
* @return the dept id
*/
public Long getDeptId()
{
return deptId;
}
/**
* Sets the dept id.
*
* @param deptId
* the new dept id
*/
public void setDeptId(Long deptId)
{
this.deptId = deptId;
}
/**
* Gets the employee id.
*
* @return the employee id
*/
public Long getEmployeeId()
{
return employeeId;
}
/**
* Sets the employee id.
*
* @param employeeId
* the new employee id
*/
public void setEmployeeId(Long employeeId)
{
this.employeeId = employeeId;
}
/**
* Gets the department name.
*
* @return the department name
*/
public String getDepartmentName()
{
return departmentName;
}
/**
* Sets the department name.
*
* @param departmentName
* the new department name
*/
public void setDepartmentName(String departmentName)
{
this.departmentName = departmentName;
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Employee.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.impetus.core.DefaultKunderaEntity;
/**
* The Class Employee.
*/
@Entity
public class Employee extends DefaultKunderaEntity
{
/** The employee id. */
@Id
private Long employeeId;
/** The salary. */
private Double salary;
/** The name. */
private String name;
/**
* Gets the emplyoee id.
*
* @return the emplyoee id
*/
public Long getEmplyoeeId()
{
return employeeId;
}
/**
* Sets the emplyoee id.
*
* @param emplyoeeId
* the new emplyoee id
*/
public void setEmplyoeeId(Long emplyoeeId)
{
this.employeeId = emplyoeeId;
}
/**
* Gets the salary.
*
* @return the salary
*/
public Double getSalary()
{
return salary;
}
/**
* Sets the salary.
*
* @param salary
* the new salary
*/
public void setSalary(Double salary)
{
this.salary = salary;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName()
{
return name;
}
/**
* Sets the name.
*
* @param name
* the new name
*/
public void setName(String name)
{
this.name = name;
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Tweets.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.impetus.core.DefaultKunderaEntity;
/**
* The Class Tweets.
*
* @author impetus
*
* Tweets entity
*/
@Entity
public class Tweets extends DefaultKunderaEntity
{
/** The tweet id. */
@Id
@Column(name = "tweet_id")
private String tweetId;
/** The body. */
@Column(name = "body")
private String body;
/** The tweet date. */
@Column(name = "tweeted_at")
@Temporal(TemporalType.DATE)
private Date tweetDate;
/** The videos. */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "tweet_id")
private Set videos;
/**
* Instantiates a new tweets.
*/
public Tweets()
{
// Default constructor.
}
/**
* Gets the tweet id.
*
* @return the tweetId
*/
public String getTweetId()
{
return tweetId;
}
/**
* Sets the tweet id.
*
* @param tweetId
* the tweetId to set
*/
public void setTweetId(String tweetId)
{
this.tweetId = tweetId;
}
/**
* Gets the body.
*
* @return the body
*/
public String getBody()
{
return body;
}
/**
* Sets the body.
*
* @param body
* the body to set
*/
public void setBody(String body)
{
this.body = body;
}
/**
* Gets the tweet date.
*
* @return the tweetDate
*/
public Date getTweetDate()
{
return tweetDate;
}
/**
* Sets the tweet date.
*
* @param tweetDate
* the tweetDate to set
*/
public void setTweetDate(Date tweetDate)
{
this.tweetDate = tweetDate;
}
/**
* Gets the videos.
*
* @return the videos
*/
public Set getVideos()
{
return videos;
}
/**
* Sets the videos.
*
* @param videos
* the new videos
*/
public void setVideos(Set videos)
{
this.videos = videos;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "Tweets [tweetId=" + tweetId + ", body=" + body + ", tweetDate=" + tweetDate + ", videos=" + videos
+ "]";
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/User.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import com.impetus.core.DefaultKunderaEntity;
/**
* The Class User.
*
* @author impetus User entity.
*/
@Entity
public class User extends DefaultKunderaEntity
{
/** The user id. */
@Id
@Column(name = "user_id")
private String userId;
/** The first name. */
@Column(name = "first_name")
private String firstName;
/** The last name. */
@Column(name = "last_name")
private String lastName;
/** The email id. */
@Column(name = "emailId")
private String emailId;
/** The tweets. */
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private Set tweets;
/**
* Instantiates a new user.
*/
public User()
{
}
/**
* Gets the user id.
*
* @return the userId
*/
public String getUserId()
{
return userId;
}
/**
* Sets the user id.
*
* @param userId
* the userId to set
*/
public void setUserId(String userId)
{
this.userId = userId;
}
/**
* Gets the first name.
*
* @return the firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* Sets the first name.
*
* @param firstName
* the firstName to set
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
/**
* Gets the last name.
*
* @return the lastName
*/
public String getLastName()
{
return lastName;
}
/**
* Sets the last name.
*
* @param lastName
* the lastName to set
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
}
/**
* Gets the email id.
*
* @return the emailId
*/
public String getEmailId()
{
return emailId;
}
/**
* Sets the email id.
*
* @param emailId
* the emailId to set
*/
public void setEmailId(String emailId)
{
this.emailId = emailId;
}
/**
* Gets the tweets.
*
* @return the tweets
*/
public Set getTweets()
{
return tweets;
}
/**
* Sets the tweets.
*
* @param tweets
* the tweets to set
*/
public void setTweets(Set tweets)
{
this.tweets = tweets;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "User [userId=" + userId + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId
+ ", tweets=" + tweets + "]";
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (userId == null)
{
if (other.userId != null)
return false;
}
else if (!userId.equals(other.userId))
return false;
return true;
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Video.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.impetus.core.DefaultKunderaEntity;
/**
* The Class Video.
*
* @author impetus
*
* Video entity
*/
@Entity
public class Video extends DefaultKunderaEntity
{
/** The video id. */
@Id
@Column(name = "video_id")
private String videoId;
/** The video name. */
@Column(name = "video_name")
private String videoName;
/** The video provider. */
@Column(name = "video_provider")
private String videoProvider;
/**
* Instantiates a new video.
*/
public Video()
{
// Default constructor.
}
/**
* Gets the video id.
*
* @return the video id
*/
public String getVideoId()
{
return videoId;
}
/**
* Sets the video id.
*
* @param videoId
* the new video id
*/
public void setVideoId(String videoId)
{
this.videoId = videoId;
}
/**
* Gets the video name.
*
* @return the video name
*/
public String getVideoName()
{
return videoName;
}
/**
* Sets the video name.
*
* @param videoName
* the new video name
*/
public void setVideoName(String videoName)
{
this.videoName = videoName;
}
/**
* Gets the video provider.
*
* @return the video provider
*/
public String getVideoProvider()
{
return videoProvider;
}
/**
* Sets the video provider.
*
* @param videoProvider
* the new video provider
*/
public void setVideoProvider(String videoProvider)
{
this.videoProvider = videoProvider;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return "Video [videoId=" + videoId + ", videoName=" + videoName + ", videoProvider=" + videoProvider + "]";
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/polyglot/PolyglotTest.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.polyglot;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.kundera.dataasobject.entities.Tweets;
import com.impetus.kundera.dataasobject.entities.User;
import com.impetus.kundera.dataasobject.entities.Video;
import junit.framework.Assert;
/**
* The Class PolyglotTest.
*/
public class PolyglotTest
{
/**
* Sets the up before class.
*/
@BeforeClass
public static void SetUpBeforeClass()
{
User.bind("client-polyglot-properties.json", User.class);
}
/**
* Test polyglot.
*/
@Test
public void testPolyglot()
{
testInsert();
testQuery();
testDelete();
}
/**
* Test insert.
*/
private void testInsert()
{
User user = new User();
user.setFirstName("Devender");
user.setLastName("Yadav");
user.setUserId("u-101");
user.setEmailId("devender.yadav@impetus.co.in");
Set tweetSet = new HashSet<>();
Tweets tweet1 = new Tweets();
tweet1.setTweetId("t-101");
tweet1.setBody("this is tweet 1");
tweet1.setTweetDate(new Date());
Set videoSet = new HashSet<>();
Video video1 = new Video();
video1.setVideoId("v-101");
video1.setVideoName("movie");
video1.setVideoProvider("netflix");
videoSet.add(video1);
tweet1.setVideos(videoSet);
tweetSet.add(tweet1);
user.setTweets(tweetSet);
user.save();
User u = new User().find("u-101");
validateUser(u);
}
/**
* Test query.
*/
private void testQuery()
{
List users = new User().query("select u from User u");
Assert.assertEquals(1, users.size());
User u = users.get(0);
validateUser(u);
users = null;
users = new User().query("select u from User u where u.emailId = 'devender.yadav@impetus.co.in'");
validateUser(u);
}
/**
* Test delete.
*/
private void testDelete()
{
User u = new User().find("u-101");
u.delete();
User u1 = new User().find("u-101");
Assert.assertNull(u1);
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
User.unbind();
}
/**
* Validate user.
*
* @param u
* the u
*/
private void validateUser(User u)
{
Assert.assertEquals("Devender", u.getFirstName());
Assert.assertEquals("Yadav", u.getLastName());
Assert.assertEquals("u-101", u.getUserId());
Assert.assertEquals("devender.yadav@impetus.co.in", u.getEmailId());
Set tweets = u.getTweets();
Assert.assertEquals(1, tweets.size());
Tweets t = tweets.iterator().next();
Assert.assertEquals("t-101", t.getTweetId());
Assert.assertEquals("this is tweet 1", t.getBody());
Set videos = t.getVideos();
Assert.assertEquals(1, videos.size());
Video v = videos.iterator().next();
Assert.assertEquals("v-101", v.getVideoId());
Assert.assertEquals("movie", v.getVideoName());
Assert.assertEquals("netflix", v.getVideoProvider());
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/query/BookBaseTest.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.query;
import java.util.List;
import com.impetus.kundera.dataasobject.entities.Book;
import junit.framework.Assert;
/**
* The Class BookBaseTest.
*
* @author Pragalbh Garg
*/
public abstract class BookBaseTest
{
/** The t. */
protected boolean T = true;
/** The f. */
protected boolean F = false;
/**
* Validate book1.
*
* @param book
* the book
*/
protected void validateBook1(Book book)
{
Assert.assertNotNull(book);
Assert.assertEquals(Integer.valueOf(1), book.getBookId());
Assert.assertEquals("book1", book.getTitle());
Assert.assertEquals("author1", book.getAuthor());
Assert.assertEquals(2000, book.getYear());
Assert.assertEquals(100, book.getPages());
}
/**
* Validate book2.
*
* @param book
* the book
*/
protected void validateBook2(Book book)
{
Assert.assertNotNull(book);
Assert.assertEquals(Integer.valueOf(2), book.getBookId());
Assert.assertEquals("book2", book.getTitle());
Assert.assertEquals("author2", book.getAuthor());
Assert.assertEquals(2005, book.getYear());
Assert.assertEquals(200, book.getPages());
}
/**
* Validate book3.
*
* @param book
* the book
*/
protected void validateBook3(Book book)
{
Assert.assertNotNull(book);
Assert.assertEquals(Integer.valueOf(3), book.getBookId());
Assert.assertEquals("book3", book.getTitle());
Assert.assertEquals("author3", book.getAuthor());
Assert.assertEquals(2010, book.getYear());
Assert.assertEquals(300, book.getPages());
}
/**
* Validate book4.
*
* @param book
* the book
*/
protected void validateBook4(Book book)
{
Assert.assertNotNull(book);
Assert.assertEquals(Integer.valueOf(4), book.getBookId());
Assert.assertEquals("book4", book.getTitle());
Assert.assertEquals("author1", book.getAuthor());
Assert.assertEquals(2015, book.getYear());
Assert.assertEquals(400, book.getPages());
}
/**
* Assert results.
*
* @param results
* the results
* @param foundBook1
* the found book1
* @param foundBook2
* the found book2
* @param foundBook3
* the found book3
* @param foundBook4
* the found book4
*/
protected void assertResults(List results, boolean foundBook1, boolean foundBook2, boolean foundBook3,
boolean foundBook4)
{
for (Book book : (List) results)
{
switch (book.getBookId())
{
case 1:
if (foundBook1)
validateBook1(book);
else
Assert.fail();
break;
case 2:
if (foundBook2)
validateBook2(book);
else
Assert.fail();
break;
case 3:
if (foundBook3)
validateBook3(book);
else
Assert.fail();
break;
case 4:
if (foundBook4)
validateBook4(book);
else
Assert.fail();
break;
}
}
}
/**
* Assert deleted.
*
* @param foundBook1
* the b1
* @param foundBook2
* the b2
* @param foundBook3
* the b3
* @param foundBook4
* the b4
*/
protected void assertDeleted(Boolean foundBook1, Boolean foundBook2, Boolean foundBook3, Boolean foundBook4)
{
Book book1 = new Book().find(1);
Book book2 = new Book().find(2);
Book book3 = new Book().find(3);
Book book4 = new Book().find(4);
if (foundBook1)
{
Assert.assertNull(book1);
}
else
{
Assert.assertNotNull(book1);
}
if (foundBook2)
{
Assert.assertNull(book2);
}
else
{
Assert.assertNotNull(book2);
}
if (foundBook3)
{
Assert.assertNull(book3);
}
else
{
Assert.assertNotNull(book3);
}
if (foundBook4)
{
Assert.assertNull(book4);
}
else
{
Assert.assertNotNull(book4);
}
}
}
================================================
FILE: examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/query/CassandraQueryTest.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.dataasobject.query;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.core.QueryType;
import com.impetus.kundera.dataasobject.entities.Book;
import junit.framework.Assert;
/**
* The Class CassandraQueryTest.
*
* @author Devender Yadav
*/
public class CassandraQueryTest extends BookBaseTest
{
/**
* Sets the up before class.
*
* @throws Exception
* the exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
Book.bind("client-properties.json", Book.class);
}
/**
* Sets the up.
*
* @throws Exception
* the exception
*/
@Before
public void setUp() throws Exception
{
persistBooks();
}
/**
* Test select queries.
*
* @throws Exception
* the exception
*/
@Test
public void testSelectQueries() throws Exception
{
testSelectAll();
testSelectOnId();
testSelectWithWhereClause();
testSelectFields();
}
/**
* Test native queries.
*/
@Test
public void testNativeQueries()
{
List results = new Book().query("select \"TITLE\" from \"Book\"", QueryType.NATIVE);
Assert.assertNotNull(results);
Assert.assertEquals(4, results.size());
results = new Book().query("select \"AUTHOR\" from \"Book\" where token(\"ID\") = token(1)", QueryType.NATIVE);
Assert.assertNotNull(results);
Assert.assertEquals(1, results.size());
Assert.assertEquals("author1", ((Book) results.get(0)).getAuthor());
}
/**
* Test select all.
*/
private void testSelectAll()
{
List results = new Book().query("select b from Book b");
Assert.assertNotNull(results);
Assert.assertEquals(4, results.size());
Assert.assertTrue(Book.class.isAssignableFrom(results.get(0).getClass()));
assertResults(results, T, T, T, T);
}
/**
* Test select on id.
*/
private void testSelectOnId()
{
List results = new Book().query("select b from Book b where b.bookId=1");
Assert.assertNotNull(results);
Assert.assertEquals(1, results.size());
validateBook1(results.get(0));
results = new Book().query("select b from Book b where b.bookId in (3,4,5,6)");
Assert.assertNotNull(results);
Assert.assertEquals(2, results.size());
assertResults(results, F, F, T, T);
}
/**
* Test select with where clause.
*/
private void testSelectWithWhereClause()
{
List results = new Book().query("select b from Book b where b.title = 'book1'");
Assert.assertNotNull(results);
validateBook1(results.get(0));
results = new Book().query("select b from Book b where b.author = 'author2'");
Assert.assertNotNull(results);
validateBook2(results.get(0));
results = new Book().query("select b from Book b where b.year = 2005");
Assert.assertNotNull(results);
Assert.assertEquals(1, results.size());
validateBook2(results.get(0));
}
/**
* Test select fields.
*/
private void testSelectFields()
{
List results = new Book().query("select b.title from Book b");
Assert.assertNotNull(results);
Assert.assertEquals(4, results.size());
results = new Book().query("select b.author from Book b where b.bookId=1");
Assert.assertNotNull(results);
Assert.assertEquals(1, results.size());
Assert.assertEquals("author1", ((Book) results.get(0)).getAuthor());
results = new Book().query("select b.title from Book b where b.bookId in (3,4,5,6)");
Assert.assertNotNull(results);
Assert.assertEquals(2, results.size());
}
/**
* Tear down.
*
* @throws Exception
* the exception
*/
@After
public void tearDown() throws Exception
{
deleteBooks();
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
Book.unbind();
}
/**
* Persist books.
*/
private void persistBooks()
{
Book book1 = prepareData(1, "book1", "author1", 2000, 100);
Book book2 = prepareData(2, "book2", "author2", 2005, 200);
Book book3 = prepareData(3, "book3", "author3", 2010, 300);
Book book4 = prepareData(4, "book4", "author1", 2015, 400);
book1.save();
book2.save();
book3.save();
book4.save();
}
/**
* Delete books.
*/
private void deleteBooks()
{
Book b1 = new Book().find(1);
b1.delete();
Book b2 = new Book().find(2);
b2.delete();
Book b3 = new Book().find(3);
b3.delete();
Book b4 = new Book().find(4);
b4.delete();
}
/**
* Prepare data.
*
* @param bookId
* the book id
* @param title
* the title
* @param author
* the author
* @param year
* the year
* @param pages
* the pages
* @return the book
*/
private Book prepareData(int bookId, String title, String author, int year, int pages)
{
Book book = new Book();
book.setBookId(bookId);
book.setTitle(title);
book.setAuthor(author);
book.setYear(year);
book.setPages(pages);
return book;
}
}
================================================
FILE: examples/data-as-object-example/src/test/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.dataasobject.entities.User
true
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.dataasobject.entities.Tweets
true
com.impetus.kundera.KunderaPersistence
com.impetus.kundera.dataasobject.entities.Video
true
================================================
FILE: examples/data-as-object-example/src/test/resources/client-polyglot-properties.json
================================================
{
"com.impetus.kundera.dataasobject.entities.User": {
"kundera.pu":"twirdbms"
},
"com.impetus.kundera.dataasobject.entities.Tweets": {
"kundera.pu":"twingo"
},
"com.impetus.kundera.dataasobject.entities.Video": {
"kundera.pu":"twissandra"
}
}
================================================
FILE: examples/data-as-object-example/src/test/resources/client-properties-all.json
================================================
{
"all": {
"kundera.nodes": "localhost",
"kundera.port": "9160",
"kundera.client": "cassandra",
"kundera.keyspace": "DAOTest",
"kundera.ddl.auto.prepare": "update",
"cql.version": "3.0.0",
"kundera.client.lookup.class": "com.impetus.client.cassandra.thrift.ThriftClientFactory"
}
}
================================================
FILE: examples/data-as-object-example/src/test/resources/client-properties.json
================================================
{
"com.impetus.kundera.dataasobject.entities.Employee,com.impetus.kundera.dataasobject.entities.Department": {
"kundera.nodes": "localhost",
"kundera.port": "9160",
"kundera.client": "cassandra",
"kundera.keyspace": "DAOTest",
"kundera.ddl.auto.prepare": "update",
"cql.version": "3.0.0",
"kundera.client.lookup.class": "com.impetus.client.cassandra.thrift.ThriftClientFactory"
},
"com.impetus.kundera.dataasobject.entities.Book": {
"kundera.nodes": "localhost",
"kundera.port": "9160",
"kundera.client": "cassandra",
"kundera.keyspace": "DAOTest",
"kundera.ddl.auto.prepare": "update",
"cql.version": "3.0.0",
"kundera.client.lookup.class": "com.impetus.client.cassandra.thrift.ThriftClientFactory"
},
"com.impetus.kundera.dataasobject.entities.Customer": {
"kundera.nodes": "quickstart.cloudera",
"kundera.port": "7051",
"kundera.client": "kudu",
"kundera.keyspace": "DAOTest",
"kundera.ddl.auto.prepare": "create",
"kundera.client.lookup.class": "com.impetus.client.kudu.KuduDBClientFactory"
},
"com.impetus.kundera.dataasobject.entities.DepartmentKudu": {
"kundera.nodes": "quickstart.cloudera",
"kundera.port": "7051",
"kundera.client": "kudu",
"kundera.keyspace": "DAOTest",
"kundera.ddl.auto.prepare": "create",
"kundera.client.lookup.class": "com.impetus.client.kudu.KuduDBClientFactory"
}
}
================================================
FILE: examples/polyglot/kvapps/pom.xml
================================================
4.0.0
com.impetus
kvapps
1.0
jar
kvapps
http://maven.apache.org
UTF-8
3.3-SNAPSHOT
sonatype-nexus
Kundera Public Repository
https://oss.sonatype.org/content/repositories/releases
true
false
kundera-missing
Kundera Public Missing Resources Repository
http://kundera.googlecode.com/svn/maven2/maven-missing-resources
true
true
com.impetus.kundera.client
kundera-cassandra
${kundera.version}
com.impetus.kundera.client
kundera-rdbms
${kundera.version}
com.impetus.kundera.client
kundera-mongo
${kundera.version}
mysql
mysql-connector-java
5.1.9
junit
junit
4.5
test
org.apache.poi
poi
3.9
org.apache.maven.wagon
wagon-webdav
1.0-beta-2
maven-compiler-plugin
1.7
1.7
org.apache.maven.plugins
maven-clean-plugin
${basedir}
cobertura.ser
================================================
FILE: examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/PersonalDetail.java
================================================
/*
* Copyright 2011 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kvapps.entities;
import java.io.Serializable;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* Entity class for user's personal details
*
* @author impetus
*/
@Embeddable
public class PersonalDetail {
@Column(name = "personal_detail_id")
private String personalDetailId;
@Column(name = "name")
private String name;
@Column(name = "password")
private String password;
@Column(name = "rel_status")
private String relationshipStatus;
public PersonalDetail() {
}
public PersonalDetail(String name, String password,
String relationshipStatus) {
setPersonalDetailId(UUID.randomUUID().toString());
setName(name);
setPassword(password);
setRelationshipStatus(relationshipStatus);
}
/**
* @return the personalDetailId
*/
public String getPersonalDetailId() {
return personalDetailId;
}
/**
* @param personalDetailId
* the personalDetailId to set
*/
public void setPersonalDetailId(String personalDetailId) {
this.personalDetailId = personalDetailId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the relationshipStatus
*/
public String getRelationshipStatus() {
return relationshipStatus;
}
/**
* @param relationshipStatus
* the relationshipStatus to set
*/
public void setRelationshipStatus(String relationshipStatus) {
this.relationshipStatus = relationshipStatus;
}
public PersonalDetail(String personalDetailId, String name,
String password, String relationshipStatus) {
super();
this.personalDetailId = personalDetailId;
this.name = name;
this.password = password;
this.relationshipStatus = relationshipStatus;
}
}
================================================
FILE: examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/Tweets.java
================================================
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kvapps.entities;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* @author impetus
*
* Tweets entity
*/
@Entity
@Table(name = "tweets")
@IndexCollection(columns = { @Index(name = "body"), @Index(name = "tweeted_at") })
public class Tweets
{
@Id
@Column(name = "tweet_id")
private String tweetId;
@Column(name = "body")
private String body;
@Column(name = "tweeted_at")
@Temporal(TemporalType.DATE)
private Date tweetDate;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "tweet_id")
private Set videos;
public Tweets()
{
// Default constructor.
}
/**
* @return the tweetId
*/
public String getTweetId()
{
return tweetId;
}
/**
* @param tweetId
* the tweetId to set
*/
public void setTweetId(String tweetId)
{
this.tweetId = tweetId;
}
/**
* @return the body
*/
public String getBody()
{
return body;
}
/**
* @param body
* the body to set
*/
public void setBody(String body)
{
this.body = body;
}
/**
* @return the tweetDate
*/
public Date getTweetDate()
{
return tweetDate;
}
/**
* @param tweetDate
* the tweetDate to set
*/
public void setTweetDate(Date tweetDate)
{
this.tweetDate = tweetDate;
}
public Set getVideos()
{
return videos;
}
public void setVideos(Set videos)
{
this.videos = videos;
}
@Override
public String toString()
{
return "Tweets [tweetId=" + tweetId + ", body=" + body + ", tweetDate=" + tweetDate + ", videos=" + videos
+ "]";
}
}
================================================
FILE: examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/User.java
================================================
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kvapps.entities;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.impetus.kundera.index.Index;
import com.impetus.kundera.index.IndexCollection;
/**
* @author impetus
* User entity.
*/
@Entity
@Table(name = "User")
@IndexCollection(columns = { @Index(name = "emailId") })
public class User {
@Id
@Column(name = "user_id")
private String userId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "emailId")
private String emailId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private Set tweets;
@Embedded
private PersonalDetail personalDetail;
public User() {
// Default constructor.
}
/**
* @return the userId
*/
public String getUserId() {
return userId;
}
/**
* @param userId
* the userId to set
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName
* the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName
* the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the emailId
*/
public String getEmailId() {
return emailId;
}
/**
* @param emailId
* the emailId to set
*/
public void setEmailId(String emailId) {
this.emailId = emailId;
}
/**
* @return the tweets
*/
public Set getTweets() {
return tweets;
}
/**
* @param tweets
* the tweets to set
*/
public void setTweets(Set tweets) {
this.tweets = tweets;
}
public PersonalDetail getPersonalDetail() {
return personalDetail;
}
public void setPersonalDetail(PersonalDetail personalDetail) {
this.personalDetail = personalDetail;
}
@Override
public String toString() {
return "User [userId=" + userId + ", firstName=" + firstName
+ ", lastName=" + lastName + ", emailId=" + emailId
+ ", tweets=" + tweets + ", personalDetail=" + personalDetail
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userId == null) ? 0 : userId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (userId == null) {
if (other.userId != null)
return false;
} else if (!userId.equals(other.userId))
return false;
return true;
}
}
================================================
FILE: examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/Video.java
================================================
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kvapps.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author impetus
*
* Video entity
*/
@Entity
@Table(name = "video")
public class Video {
@Id
@Column(name = "video_id")
private String videoId;
@Column(name = "video_name")
private String videoName;
@Column(name = "video_provider")
private String videoProvider;
public Video() {
// Default constructor.
}
public String getVideoId() {
return videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public String getVideoName() {
return videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public String getVideoProvider() {
return videoProvider;
}
public void setVideoProvider(String videoProvider) {
this.videoProvider = videoProvider;
}
@Override
public String toString() {
return "Video [videoId=" + videoId + ", videoName=" + videoName
+ ", videoProvider=" + videoProvider + "]";
}
}
================================================
FILE: examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/runner/AppRunner.java
================================================
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kvapps.runner;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.impetus.kvapps.entities.User;
/**
* @author impetus
*
* Sample Application runner. Application demonstrates:
* poly glot persistence, where user information {@link User} is getting persisted into mysql and corresponding tweets into Cassandra.
* Fetch user(alongwith tweets) in polyglot way
* Fetch tweets using native query support
* Since {kundera.ddl.auto.prepare} is set to "create"(Please refer src/main/resources/persistence.xml).
* hence schema will be automatically managed by Kundera itself.
*
* Also, application takes path to excel data file as an input arguments.
*/
public class AppRunner
{
/** the log used by this class. */
private static Log logger = LogFactory.getLog(AppRunner.class);
/**
* main runner method
* @param args takes excel data file as input argument args[0].
*/
public static void main(String[] args)
{
// Override CQL version while instantiating entity manager factory.
EntityManagerFactory emf = Persistence.createEntityManagerFactory("twissandra,twingo,twirdbms");
EntityManager em = emf.createEntityManager();
try
{
//populate user set from excel sheet.
Set users = UserBroker.brokeUserList(args[0]);
for (Iterator iterator = users.iterator(); iterator.hasNext();)
{
User user = (User) iterator.next();
// on Persist
ExecutorService.onPersist(em, user);
// on find by id.
ExecutorService.findByKey(em,"BigDataUser");
List fetchedUsers = ExecutorService.onQueryByEmail(em, user);
if (fetchedUsers != null && fetchedUsers.size() > 0)
{
logger.info(user.toString());
}
logger.info("");
System.out.println("#######################Querying##########################################");
logger.info("");
logger.info("");
}
// Execute wild search query.
String query = "Select u from User u";
logger.info(query);
ExecutorService.findByQuery(em, query);
// // Execute native CQL. Fetch tweets for given user.
logger.info("");
System.out.println("#######################Querying##########################################");
logger.info("");
logger.info("");
query = "Select * from tweets where user_id='RDBMSUser'";
logger.info(query);
ExecutorService.findByNativeQuery(em,query);
} finally
{
onDestroyDBResources(emf, em);
}
}
/**
* After successful processing close entity manager and it's factory instance.
*
* @param emf entity manager factory instance.
* @param em entity manager instance
*/
private static void onDestroyDBResources(EntityManagerFactory emf,EntityManager em) {
if(emf != null)
{
emf.close();
}
if(em != null)
{
em.close();
}
}
}
================================================
FILE: examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/runner/ExecutorService.java
================================================
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kvapps.runner;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.impetus.client.cassandra.common.CassandraConstants;
import com.impetus.client.cassandra.thrift.ThriftClient;
import com.impetus.kundera.client.Client;
import com.impetus.kvapps.entities.Tweets;
import com.impetus.kvapps.entities.User;
import com.impetus.kvapps.entities.Video;
/**
* @author impetus
*
* Executor service, responsible for performing various CRUD operation on {@link User} in polyglot way.
*
*/
public final class ExecutorService {
/** the log used by this class. */
private static Log logger = LogFactory.getLog(ExecutorService.class);
/**
* on query with user email id
*
* @param em entity manager instance.
* @param user user entity instance.
* @return collection of user instance.
*/
static List onQueryByEmail(final EntityManager em, final User user)
{
// Query by parameter (fetch user by email id)
String query = "Select u from User u where u.emailId =?1";
logger.info("");
logger.info("");
logger.info(query);
System.out.println("#######################Querying##########################################");
// find by named parameter(e.g. email)
List fetchedUsers = findByEmail(em, query, user.getEmailId());
return fetchedUsers;
}
/**
* On persist user.
*
* @param em entity manager instance.
* @param user user object.
*/
static void onPersist(final EntityManager em, final User user)
{
logger.info("");
logger.info("");
logger.info("#######################Persisting##########################################");
logger.info("");
logger.info(user.toString());
persist(user, em);
logger.info("");
System.out.println("#######################Persisting##########################################");
logger.info("");
logger.info("");
}
/**
* On find by user id.
*
* @param em entity manager instance.
* @param userId user id.
*/
static User findByKey(final EntityManager em, final String userId)
{
User user = em.find(User.class, userId);
logger.info("[On Find by key]");
System.out.println("#######################START##########################################");
logger.info("\n");
logger.info("\t\t User's first name:" + user.getFirstName());
logger.info("\t\t User's emailId:" + user.getEmailId());
logger.info("\t\t User's Personal Details:" + user.getPersonalDetail().getName());
logger.info("\t\t User's Personal Details:" + user.getPersonalDetail().getPassword());
logger.info("\t\t User's total tweets:" + user.getTweets().size());
logger.info("\n");
System.out.println("#######################END############################################");
logger.info("\n");
return user;
}
/**
* on find by wild search query.
*
* @param em entity manager instance.
* @param query query.
*/
@SuppressWarnings("unchecked")
static void findByQuery(final EntityManager em, final String query)
{
Query q = em.createNamedQuery(query);
logger.info("[On Find All by Query]");
List users = q.getResultList();
if (users == null || users.isEmpty())
{
logger.info("0 Users Returned");
return;
}
System.out.println("#######################START##########################################");
logger.info("\t\t Total number of users:" + users.size());
logger.info("\t\t User's total tweets:" + users.get(0).getTweets().size());
printTweets(users);
logger.info("\n");
// logger.info("First tweet:" users.get(0).getTweets().);
System.out.println("#######################END############################################");
logger.info("\n");
}
/**
* On find by native CQL3 query.
*
* @param em entity manager instance.
* @param query native cql3 query.
*/
@SuppressWarnings("unchecked")
static void findByNativeQuery(final EntityManager em, final String query)
{
Query q = em.createNativeQuery(query, Tweets.class);
Map clients = (Map) em.getDelegate();
ThriftClient client = (ThriftClient) clients.get("twissandra");
client.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);
logger.info("[On Find Tweets by CQL3]");
List tweets = q.getResultList();
System.out.println("#######################START##########################################");
logger.info("\t\t User's total tweets:" + tweets.size());
onPrintTweets(tweets);
logger.info("\n");
// logger.info("First tweet:" users.get(0).getTweets().);
System.out.println("#######################END############################################");
logger.info("\n");
}
/**
* On print tweets event.
*
* @param tweets
*/
private static void onPrintTweets(final List tweets)
{
for (Iterator iterator = tweets.iterator(); iterator.hasNext();)
{
int counter = 1;
while (iterator.hasNext())
{
logger.info("\n");
logger.info("\t\t Tweet No:#" + counter++);
Tweets rec = (Tweets) iterator.next();
logger.info("\t\t tweet is ->" + rec.getBody());
logger.info("\t\t Tweeted at ->" + rec.getTweetDate());
if (rec.getVideos() != null)
{
logger.info("\t\t Tweeted Contains Video ->" + rec.getVideos().size());
for (Iterator iteratorVideo = rec.getVideos().iterator(); iteratorVideo.hasNext();)
{
Video video = (Video) iteratorVideo.next();
logger.info(video);
}
}
}
}
}
private static List findByEmail(final EntityManager em, String query, String parameter)
{
Query q = em.createNamedQuery(query);
q.setParameter(1, parameter);
List users = q.getResultList();
return users;
}
private static void printTweets(List users)
{
for (Iterator iterator = users.iterator(); iterator.hasNext();)
{
User user = (User) iterator.next();
Iterator tweets = users.get(0).getTweets().iterator();
int counter = 1;
while (tweets.hasNext())
{
logger.info("\n");
logger.info("\t\t Tweet No:#" + counter++);
Tweets rec = tweets.next();
logger.info("\t\t tweet is ->" + rec.getBody());
logger.info("\t\t Tweeted at ->" + rec.getTweetDate());
if (rec.getVideos() != null)
{
logger.info("\t\t Tweeted Contains Video ->" + rec.getVideos().size());
for (Iterator iteratorVideo = rec.getVideos().iterator(); iteratorVideo.hasNext();)
{
Video video = (Video) iteratorVideo.next();
logger.info(video);
}
}
}
}
}
/**
* @param user
*/
private static void persist(User user, final EntityManager em)
{
em.persist(user);
}
}
================================================
FILE: examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/runner/UserBroker.java
================================================
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kvapps.runner;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import com.impetus.kvapps.entities.PersonalDetail;
import com.impetus.kvapps.entities.Tweets;
import com.impetus.kvapps.entities.User;
import com.impetus.kvapps.entities.Video;
/**
* @author impetus
*
*/
public class UserBroker
{
private Sheet m_sheet;
private int m_iNbRows;
private int m_iCurrentRow = 0;
private static final String JAVA_TOSTRING = "EEE MMM dd HH:mm:ss zzz yyyy";
public UserBroker(Sheet sheet)
{
m_sheet = sheet;
m_iNbRows = sheet.getPhysicalNumberOfRows();
}
/*
* Returns the contents of an Excel row in the form of a String array.
*
* @see com.ibm.ccd.common.parsing.Parser#splitLine()
*/
public User addUser(Set users) throws Exception
{
if (m_iCurrentRow == m_iNbRows)
return null;
Row row = m_sheet.getRow(m_iCurrentRow);
if (row == null)
{
return null;
}
else
{
// extract fields from excel sheet
String userName = extractCellData(row, 0);
String tweetBody = extractCellData(row, 1);
String videoId = extractCellData(row, 2);
String videoName = extractCellData(row, 3);
User user = null;
boolean present = false;
//iterate over fields.
for (Iterator iterator = users.iterator(); iterator.hasNext();)
{
user = (User) iterator.next();
if (user.getFirstName().equals(userName))
{
present = true;
break;
}
}
if (!present)
{
user = addUser(userName);
}
Tweets tweet = addTweets(user, tweetBody, new Date(), m_iCurrentRow + "");
assignVideosToTweet(tweet, videoId, videoName);
m_iCurrentRow++;
return user;
}
}
/*
* Populates user instance for provided userName attribute.
*/
private User addUser(String userName)
{
User user = new User();
PersonalDetail personalDetail = new PersonalDetail(userName, userName + "Password", "Single");
user.setUserId(userName);
user.setEmailId(userName + "@" + userName + ".com");
user.setFirstName(userName);
user.setLastName(userName);
user.setTweets(new HashSet());
user.setPersonalDetail(personalDetail);
return user;
}
/*
* Add user's tweets to provided user object.
*/
private static Tweets addTweets(User user, String body, Date tweetDate, String tweetId)
{
Tweets tweet = new Tweets();
tweet.setTweetId(tweetId);
tweet.setBody(body);
tweet.setTweetDate(tweetDate);
user.getTweets().add(tweet);
return tweet;
}
/*
* Upload a collection of videos for a specific tweet.
*/
private static void assignVideosToTweet(Tweets tweet, String videoId, String videoName)
{
Set videos = new HashSet();
Video video = new Video();
video.setVideoId(videoId);
video.setVideoName(videoName);
videos.add(video);
tweet.setVideos(videos);
}
/*
* Read a cell for specific column.
*/
private String extractCellData(Row row, int iCurrent) throws Exception
{
Cell cell = (Cell) row.getCell(iCurrent);
if (cell == null)
{
return "";
}
else
{
switch (cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:
double value = cell.getNumericCellValue();
if (HSSFDateUtil.isCellDateFormatted(cell))
{
if (HSSFDateUtil.isValidExcelDate(value))
{
Date date = HSSFDateUtil.getJavaDate(value);
SimpleDateFormat dateFormat = new SimpleDateFormat(JAVA_TOSTRING);
return dateFormat.format(date);
}
else
{
throw new Exception("Invalid Date value found at row number " + row.getRowNum()
+ " and column number " + cell.getColumnIndex());
}
}
else
{
return value + "";
}
case HSSFCell.CELL_TYPE_STRING:
return cell.getStringCellValue();
case HSSFCell.CELL_TYPE_BLANK:
return null;
default:
return null;
}
}
}
/**
* Reads and populate a collection of {@link User} from excel file available at dataFilePath.
*
* @param dataFilePath
* @return collection of users.
*/
static Set brokeUserList(final String dataFilePath)
{
Set users = new HashSet();
Workbook workBook = null;
File file = new File(dataFilePath);
InputStream excelDocumentStream = null;
try
{
excelDocumentStream = new FileInputStream(file);
POIFSFileSystem fsPOI = new POIFSFileSystem(new BufferedInputStream(excelDocumentStream));
workBook = new HSSFWorkbook(fsPOI);
UserBroker parser = new UserBroker(workBook.getSheetAt(0));
User user;
while ((user = parser.addUser(users)) != null)
{
users.add(user);
}
excelDocumentStream.close();
}
catch (Exception e)
{
throw new RuntimeException("Error while processing brokeUserList(), Caused by :",e);
}
return users;
}
}
================================================
FILE: examples/polyglot/kvapps/src/main/resources/KunderaConnection.xml
================================================
cassandra
================================================
FILE: examples/polyglot/kvapps/src/main/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
com.impetus.kvapps.entities.User
true
com.impetus.kundera.KunderaPersistence
com.impetus.kvapps.entities.Tweets
true
com.impetus.kundera.KunderaPersistence
com.impetus.kvapps.entities.Video
true
================================================
FILE: examples/polyglot/kvapps/src/main/resources/log4j.properties
================================================
log4j.rootLogger=FATAL, DRFA, CONSOLE
### direct log messages to stdout ###
log4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DRFA.File=${user.home}/kundera.log
# Rollover at midnight
log4j.appender.DRFA.DatePattern=.yyyy-MM-dd
log4j.appender.DRFA.layout=org.apache.log4j.PatternLayout
# Pattern format: Date LogLevel LoggerName LogMessage
log4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%m%n
log4j.category.com.impetus.kvapps=INFO
================================================
FILE: examples/pom.xml
================================================
4.0.0
com.impetus
kundera-parent
3.3-SNAPSHOT
com.impetus.kundera
examples
3.3-SNAPSHOT
pom
examples
https://github.com/impetus-opensource/Kundera
The Apache Software License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0.txt
repo
scm:git:git@github.com:impetus-opensource/Kundera.git
scm:git:git@github.com:impetus-opensource/Kundera.git
git@github.com:impetus-opensource/Kundera.git
vivek.mishra
Vivek Mishra
vivek.mishra@yahoo.com
amresh.singh
Amresh Kumar Singh
amresh1002@gmail.com
Kuldeep.mishra
Kuldeep Kumar Mishra
kuld.cs.mishra@gmail.com
UTF-8
UTF-8
jacoco
reuseReports
java
clover
Clover maven repo
http://mirrors.ibiblio.org/pub/mirrors/maven
true
true
kundera-missing
Kundera Public Missing Resources Repository
http://kundera.googlecode.com/svn/maven2/maven-missing-resources
true
true
riptano
riptano
http://mvn.riptano.com/content/repositories/public
maven.scale7.org
Scale7 Maven Repo
https://github.com/s7/mvnrepo/raw/master
true
all
true
container
================================================
FILE: pom.xml
================================================
4.0.0
org.sonatype.oss
oss-parent
7
com.impetus
kundera-parent
3.14-SNAPSHOT
pom
kundera
https://github.com/Impetus/Kundera
The Apache Software License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0.txt
repo
scm:git:git@github.com:Impetus/Kundera.git
scm:git:git@github.com:Impetus/Kundera.git
git@github.com:Impetus/Kundera.git
HEAD
vivek.mishra
Vivek Mishra
vivek.mishra@impetus.co.in
devender-yadav
Devender Yadav
devender.yadav@impetus.co.in
karthikprasad13
Karthik Prasad Manchala
karthikp.manchala@impetus.co.in
UTF-8
UTF-8
jacoco
reuseReports
java
all
true
src
benchmark
test
examples
examples
release-sign-artifacts
performRelease
true
org.apache.maven.plugins
maven-gpg-plugin
sign-artifacts
verify
sign
org.apache.maven.plugins
maven-release-plugin
2.5.2
-DskipTests
default
perform
src/pom.xml
================================================
FILE: src/README.md
================================================
Overview
=========
The idea behind Kundera is to make working with NoSQL Databases drop-dead simple and fun. Kundera is being developed with following objectives:
* To make working with NoSQL as simple as working with SQL
* To serve as JPA Compliant mapping solution for NoSQL Datastores.
* To help developers, forget the complexity of NoSQL stores and focus on Domain Model.
* To make switching across data-stores as easy as changing a configuration.
[Downloads](https://github.com/impetus-opensource/Kundera/wiki/Stable-Release)
[Supported Databases](https://github.com/Impetus/Kundera/wiki/Datastores-Supported)
Note
====
With 2.9.1 release onwards artifact group id has been changed from
com.impetus.client
kundera-cassandra
2.9.1
TO
com.impetus.kundera.client
kundera-cassandra
2.9.1
Note: Above information is to notify regarding change in groupId. In case using HBase or any other supported datastore. You need to simply point to corresponding artifactId.
Up and running in 5 minutes
============================
If you have worked upon Hibernate or any JPA Compliant ORM Solution, then the whole process, right from learning to coming up with first sample implementation will not take more than 5 minutes. Please follow below steps from [this link](https://github.com/impetus-opensource/Kundera/wiki/Getting-Started-in-5-minutes "Getting started in 5 minutes"):
+ Set up Cassandra server.
+ Download and include Kundera Jar
+ Write persistence.xml file
+ Write Entity class
+ Moment of Truth!
Recent Releases
================================
#### Please Note: trunk is current development branch. kundera-3.13 is released tag.
#### 1-June-2018 - Kundera 3.13 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-313).
#### 21-December-2017 - Kundera 3.12 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-312), additional improvements and the following new features :
* Added support for storing ethereum blockchain data in Kundera supported databases. Check [wiki](https://github.com/Impetus/Kundera/wiki/Kundera-with-Ethereum-Blockchain).
#### 12-October-2017 - Kundera 3.11 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-311), additional improvements and the following new features :
* Added support for Couchbase. Check [wiki](https://github.com/Impetus/Kundera/wiki/Kundera-with-Couchbase).
* Upgraded Cassandra version to 3.11.0
#### 22-August-2017 - Kundera 3.10.1 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-3101).
#### 14-August-2017 - Kundera 3.10 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-310), additional improvements and the following new features :
* Added support for RethinkDB
#### 3-July-2017 - Kundera 3.9.1 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-391).
#### 31-May-2017 - Kundera 3.9 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-39), additional improvements and the following new features :
* MongoDB java driver updated to 3.4
* Parameterized and positional query support in Apache Kudu
#### 6-March-2017 - Kundera 3.8 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-38), additional improvements and the following new features :
* Kundera-Kudu now supports Kudu 1.2
* IN Query support added in Kundera-Kudu
* Primary key auto generation added in Kundera-Kudu
* Support for nested embeddables in Kundera-Kudu
* Support for composite primary key in Kundera-Kudu
* Secondary indexer support for ES in Kundera-Kudu
#### 6-December-2016 - Kundera 3.7 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-37), additional improvements and the following new features :
* Kundera-kudu now supports Kudu 1.x
* Support for fetch size in pagination in kundera-cassandra-ds-driver
* Support for LIKE query on rowkey in kundera-hbase-v2
#### 21-September-2016 - Kundera 3.6 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-36), additional improvements and the following new features :
* Kundera-Cassandra now supports Cassandra 3.7
* Kundera-HBase-v2 has been upgraded for HBase 1.2+
* Primary key auto-generation is added for Kundera-Elasticsearch
* Support for pagination is added to Kundera-Elasticsearch
#### 20-June-2016 - Kundera 3.5 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-35), additional improvements and the following new features :
* Kundera-Cassandra now supports Cassandra 3.5
* Kundera-Elasticsearch now supports Elasticsearch 2.3
#### 12-April-2016 - Kundera 3.4 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-34), additional improvements and the following new features :
* Support for Kudu. check [wiki](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Kudu).
* Added new light weight layer- "Data as Object". Check [wiki](https://github.com/impetus-opensource/Kundera/wiki/Kundera-Data-As-Object).
#### 16-January-2016 - Kundera 3.3 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-33), additional improvements and the following new features :
* Support for schema generation for relational entities and composite columns added with kundera-oracle-no-sql
* Support for like operator and regex enabled for kundera-hbase
* Redis 3.0 can now be used with kundera-redis
#### 16-November-2015 - Kundera 3.2 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-32), additional improvements and the following new features :
* Support for Cassandra-2.2 enabled
* Support for Oracle NoSQL 3.2.5 enabled along with schema generation.
#### 16-September-2015 - Kundera 3.1 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-31), additional improvements and the following new features :
* Querying via Apache Spark support enabled for Teradata and Hive
* Querying via Apache Spark using Kundera currently works for Cassandra, MongoDB, HDFS, Hive ,Teradata and CSV. This support is enabled using Spark 1.4.0 version.
#### 25-July-2015 - Kundera 3.0 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-30), additional improvements and the following new features :
* Apache Spark support enabled with Kundera
* Spark support with Kundera currently works for Cassandra, MongoDB, HDFS and CSV. This support is enabled with Spark 1.4.0 version.
#### 9-May-2015 - Kundera 2.17 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-217), additional improvements and the following new features :
* GridFS support added with MongoDB
* Added group by and having clause in querying support with using elastic search that can be used with other clients by using elastic search as indexer.
#### 17-March-2015 - Kundera 2.16 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-216), additional improvements and the following new features :
* Hbase data remodeling with support for HBase-1.0 version.
( Support for Hbase version 1.0 with the revised data model is available with Kundera's "kundera-hbase-v2" dependency.)
#### 2-March-2015 - Kundera 2.15.1 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-2151), additional improvements and the following new features compared to version 2.15:
* Support added for Cassandra-2.1.x version.
* Support for Cassandra User Defined Types as embeddables.
* Aggregation support available with elastic search is also enabled in Kundera
(Support for aggregate functions is also extended for other Kundera clients' by using Elastic search as indexing store.)
#### 12-January-2015 - Kundera 2.15 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-215), additional improvements and the following new features compared to version 2.14:
* Support added for Redis-2.8.x version.
* Support added for MongoDB-2.6.x version.
* Support added for Elastic-search 1.4.2 version.
#### 17-October-2014 - Kundera 2.14 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-214), additional improvements and the following new features compared to version 2.13:
* Or clause and in query support enabled for Hbase
#### 4-July-2014 - Kundera 2.13 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-213), additional improvements and the following new features compared to version 2.12:
* Support added for Hbase-0.96
* Support for composite keys over Lucene and Hbase enabled
#### 21-May-2014 - Kundera 2.12 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-212), additional improvements and the following new features compared to version 2.12:
* Support added for Oracle-KV 3.0.5
* Support for JPA-2.1 enabled
#### 24-March-2014 - Kundera 2.11 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-211), performance improvements and the following new features compared to version 2.10:
* Support added for Cassandra datastax java driver
* Support added for in clause with setParameter for collection object
#### 31-January-2014 - Kundera 2.10 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-210), performance improvements and the following new features compared to version 2.9:
* Support added for bean validation.
#### 13-December-2013 - Kundera 2.9 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-29), performance improvements and the following new features compared to version 2.8:
* Support for Secondary table.
* Support Abstract entity.
#### 21-October-2013 - Kundera 2.8 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-28), performance improvements and the following new features compared to version 2.7:
* Support for couchdb as a datastore.
* Support for MappedSuperclass and JPA Inheritence strategy.
#### 03-September-2013 - Kundera 2.7 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-27), performance improvements and the following new features compared to version 2.6:
* Support for pagination over Mongodb.
* Added elastic search as datastore and fallback indexing mechanism.
#### 06-July-2013 - Kundera 2.6 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-26), performance improvements and the following new features compared to version 2.5:
* Lazy fetching of relationships.
* Multiple node support for Cassandra.
* Pagination support for Cassandra and HBase
#### 30-Apr-2013 - Kundera 2.5 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-25), performance improvements and the following new features compared to version 2.4:
* Support for OracleNoSQL
[Please use the Oracle NoSQL jars from the Oracle NoSQL distribution at:
http://download.oracle.com/otn-pub/otn_software/nosql-database/kv-ce-2.0.26.zip.
For the convenience of those who want to build Kundera from source we have additionally
placed the jars at http://kundera.googlecode.com/svn/maven2/maven-missing-resources/]
* CQL 3.0 interoperability with thrift
#### 08-Mar-2013 - Kundera 2.4 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-24), performance improvements and the following new features compared to version 2.3:
* Support for Neo4j graph database
* Primary key auto-generation
* Support for JoinByPrimaryKey relationship
* Custom Secondary indexing hooks
* Hadoop 0.94.3 migration
#### 24-Jan-2013 - Kundera 2.3 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-23), performance improvements and the following new features compared to version 2.2:
* Redis Support
* Cassandra 1.2 migration.
* HBase schema handling changes
* Stronger query support, like selective column/id search via JPQL.
* Enabled support for @Transient for embedded columns and mapped super class.
* Record limit setting on search for mongodb .
#### 08-Nov-2012 - Kundera 2.2 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-22), performance improvements and the following new features compared to version 2.1:
* Geospatial Persistence and Queries for MongoDB
* Composite keys support for Cassandra and MongoDB
* Cassandra 1.1.6 migration
* Support for enum data type
* Named and Native queries support for REST based access
#### 21-Sep-2012 - Kundera 2.1 released
This release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-21), performance improvements and the following new features compared to version 2.0.7:
* CQL Version configuration
* Batch insert/update for Cassandra/MongoDB/HBase
* JPA MetaModel and TypedQuery implementation
* Raw thrift client support for Cassandra
* Datastore specific XML configuration. (.properties file deprecated)
* Stronger query support:
- JPQL support over all data types and associations
- JPQL support to query using primary key alongwith other columns
* JPA compliance
- EntityManager methods implementation (contains, refresh, detach, setProperty)
- EntityManagerFactory methods (getPersistenceUnitUtil)
- Persistence methods (getProviderUtil)
#### 25-July-2012 - Kundera 2.0.7 released
This release includes bug fixes, performance improvements and the following new features compared to version 2.0.6:
* HBase 0.92.1 migration
* Hadoop 1.0.2 migration
* Cassandra 1.1.2 migration
* MongoDB 2.0.4 migration
* JPA EntityTransaction commit and rollback
* JTA Transactions integration over web server
* Kundera-REST API
* Support for Counter column in cassandra
* Inverted wide-row indexing support for Cassandra
* Login Authentication support for Cassandra and MongoDB
* Filters and filters list for HBase
* Deprecated Lucene based indexing for HBase.
* Datastore specific configuration files for specifying:
- Replication factor
- Placement strategy
- Consistency level per operation.
- Counter column family configuration
- Inverted indexing switch
- Zookeeper host and port
- Hbase column family configurations
- MongoDB servers list, read preference and socket timeout.
...etc.
#### 20-Apr-2012 - Kundera 2.0.6 released
This release includes bug fixes and the following new features compared to version 2.0.5:
* HBase 0.90.x migration.
* Enhanced Persistence Context.
* Named and Native queries support (including CQL support for cassandra)
* UPDATE and DELETE queries support.
* DDL auto-schema creation.
* Performance improvements.
#### 06-Feb-2012 - Kundera 2.0.5 released
This release includes bug fixes and the following new features compared to version 2.0.4:
* Cassandra 1.x migration.
* Support for Many-to-Many relationship (via Join table)
* Transitive persistence.
* Datastore native secondary index support in addition to Lucene based indexing. An optional switch provided to change between two.
* Query support for >, < , >=,<=,!=, like, order by, like, logical operators and between.
* Connection pooling settings provided for all datastores.
* Support for all data types as required by JPA.
* Range queries for cassandra (via between clause in JPA-QL)
* Bug fixes related to self join.
#### 09-Dec-2011 - Kundera 2.0.4 released
This release includes bug fixes, performance improvements and the following new features compared to version 2.0.3:
* Cross-datastore persistence.
* Support for relational databases.
* Moved out solandra and replaced with lucene.
#### 08-Aug-2011 - Kundera 2.0.3 released
This release includes bug fixes and the following new features compared to version 2.0.2:
* Cassandra 0.8.x support added
#### 31-July-2011 - Kundera 2.0.2 released
This release includes bug fixes and the following new features compared to version 2.0.1:
* Kundera is now JPA 2.0 compliant.
* Embedded objects/ collections support for HBase.
#### 12-July-2011 - Kundera 2.0.1 released
This release includes bug fixes and the following new features compared to initial revision:
* Cassandra 0.7.x support added
* @Embedded annotation fields persisted co located with parent entity
* Search within embedded objects.
* Selective index.
[Downloads](https://github.com/impetus-opensource/Kundera/wiki/Stable-Release "Downloads")
About Us
========
Kundera is backed by Impetus Labs - iLabs. iLabs is a R&D consulting division of Impetus Technologies (http://www.impetus.com). iLabs focuses on innovations with next generation technologies and creates practice areas and new products around them. iLabs is actively involved working on High Performance computing technologies, ranging from distributed/parallel computing, Erlang, grid softwares, GPU based software, Hadoop, Hbase, Cassandra, CouchDB and related technologies. iLabs is also working on various other Open Source initiatives.
================================================
FILE: src/data-as-object/pom.xml
================================================
4.0.0
kundera
com.impetus
3.14-SNAPSHOT
com.impetus.kundera.client
data-as-object
data-as-object
http://maven.apache.org
com.impetus.kundera.core
kundera-core
${project.version}
org.codehaus.jackson
jackson-mapper-asl
1.9.13
junit
junit
4.8.2
test
maven-assembly-plugin
2.2.1
jar-with-dependencies
maven-compiler-plugin
1.7
1.7
org.apache.maven.plugins
maven-jar-plugin
2.2
test-jar
================================================
FILE: src/data-as-object/src/main/java/com/impetus/core/BindingException.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.core;
/**
* The Class BindingException.
*/
public class BindingException extends RuntimeException
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new binding exception.
*/
public BindingException()
{
super();
}
/**
* Instantiates a new binding exception.
*
* @param message
* the message
*/
public BindingException(String message)
{
super(message);
}
/**
* Instantiates a new binding exception.
*
* @param cause
* the cause
*/
public BindingException(Throwable cause)
{
super(cause);
}
/**
* Instantiates a new binding exception.
*
* @param message
* the message
* @param cause
* the cause
*/
public BindingException(String message, Throwable cause)
{
super(message, cause);
}
}
================================================
FILE: src/data-as-object/src/main/java/com/impetus/core/DefaultKunderaEntity.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Table;
import org.apache.commons.lang.StringUtils;
import com.impetus.kundera.Constants;
import com.impetus.kundera.KunderaException;
import com.impetus.kundera.configure.SchemaConfiguration;
import com.impetus.kundera.metadata.MetadataUtils;
import com.impetus.kundera.metadata.model.ApplicationMetadata;
import com.impetus.kundera.metadata.model.EntityMetadata;
import com.impetus.kundera.metadata.model.MetamodelImpl;
import com.impetus.kundera.metadata.processor.IndexProcessor;
import com.impetus.kundera.metadata.processor.TableProcessor;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;
/**
* The Class DefaultKunderaEntity.
*
* @param
* the generic type
* @param
* the key type
*/
public class DefaultKunderaEntity implements KunderaEntity
{
/** The emf. */
private static EntityManagerFactory emf;
/** The em. */
private static EntityManager em;
/*
* (non-Javadoc)
*
* @see com.impetus.core.KunderaEntity#find(java.lang.Object)
*/
public final T find(K key)
{
return (T) em.find(this.getClass(), key);
}
/**
* On bind.
*
* @param clazz
* the clazz
*/
private static void onBind(Class clazz)
{
if (((MetamodelImpl) em.getMetamodel()).getEntityMetadataMap().isEmpty())
{
EntityMetadata metadata = new EntityMetadata(clazz);
metadata.setPersistenceUnit(getPersistenceUnit());
setSchemaAndPU(clazz, metadata);
new TableProcessor(em.getEntityManagerFactory().getProperties(),
((EntityManagerFactoryImpl) em.getEntityManagerFactory()).getKunderaMetadataInstance())
.process(clazz, metadata);
KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) em.getEntityManagerFactory())
.getKunderaMetadataInstance();
new IndexProcessor(kunderaMetadata).process(clazz, metadata);
ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
((MetamodelImpl) em.getMetamodel()).addEntityMetadata(clazz, metadata);
((MetamodelImpl) em.getMetamodel()).addEntityNameToClassMapping(clazz.getSimpleName(), clazz);
appMetadata.getMetamodelMap().put(getPersistenceUnit(), em.getMetamodel());
Map> clazzToPuMap = new HashMap>();
List persistenceUnits = new ArrayList();
persistenceUnits.add(getPersistenceUnit());
clazzToPuMap.put(clazz.getName(), persistenceUnits);
appMetadata.setClazzToPuMap(clazzToPuMap);
new SchemaConfiguration(em.getEntityManagerFactory().getProperties(), kunderaMetadata, getPersistenceUnit())
.configure();
}
}
/**
* Sets the schema and pu.
*
* @param clazz
* the clazz
* @param metadata
* the metadata
*/
private static void setSchemaAndPU(Class> clazz, EntityMetadata metadata)
{
Table table = clazz.getAnnotation(Table.class);
if (table != null)
{
metadata.setTableName(!StringUtils.isBlank(table.name()) ? table.name() : clazz.getSimpleName());
String schemaStr = table.schema();
MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr,
em.getEntityManagerFactory().getProperties());
}
else
{
metadata.setTableName(clazz.getSimpleName());
metadata.setSchema((String) em.getEntityManagerFactory().getProperties().get("kundera.keyspace"));
}
if (metadata.getPersistenceUnit() == null)
{
metadata.setPersistenceUnit(getPersistenceUnit());
}
}
/**
* Gets the persistence unit.
*
* @return the persistence unit
*/
private static String getPersistenceUnit()
{
return (String) em.getEntityManagerFactory().getProperties().get(Constants.PERSISTENCE_UNIT_NAME);
}
/*
* (non-Javadoc)
*
* @see com.impetus.core.KunderaEntity#save()
*/
public final void save()
{
em.persist(this);
}
/*
* (non-Javadoc)
*
* @see com.impetus.core.KunderaEntity#update()
*/
public final void update()
{
em.merge(this);
}
/*
* (non-Javadoc)
*
* @see com.impetus.core.KunderaEntity#delete()
*/
public final void delete()
{
em.remove(this);
}
/**
* Bind.
*
* @param propertiesPath
* the properties path
* @param clazz
* the clazz
* @throws BindingException
* the binding exception
*/
public static synchronized void bind(String propertiesPath, Class clazz) throws BindingException
{
if (em == null)
{
em = PersistenceService.getEM(emf, propertiesPath, clazz.getName());
}
onBind(clazz);
}
/**
* Unbind.
*/
public static synchronized void unbind()
{
if (emf != null && emf.isOpen())
{
emf.close();
emf = null;
}
if (em != null && em.isOpen())
{
em.close();
em = null;
}
}
/*
* (non-Javadoc)
*
* @see com.impetus.core.KunderaEntity#leftJoin(java.lang.Class,
* java.lang.String, java.lang.String[])
*/
// public final List leftJoin(Class clazz, String joinColumn, String...
// columnTobeFetched)
// {
// List finalResult = new ArrayList();
// List leftTable = em.createQuery("Select p from " +
// this.getClass().getSimpleName() + " p").getResultList();
// EntityType leftEntity = ((MetamodelImpl)
// em.getMetamodel()).entity(this.getClass());
// Attribute attribute = leftEntity.getAttribute(joinColumn);
// Field field = (Field) attribute.getJavaMember();
//
// for (T obj : leftTable)
// {
// List rightTable = em
// .createQuery(
// "Select p from " + clazz.getSimpleName() + " p where p." + joinColumn + "
// = :columnValue")
// .setParameter("columnValue", PropertyAccessorHelper.getObject(obj,
// field)).getResultList();
// if (!rightTable.isEmpty())
// {
// finalResult.add(obj);
// }
// }
// return finalResult;
// }
/*
* (non-Javadoc)
*
* @see com.impetus.core.KunderaEntity#query(java.lang.String)
*/
public List query(String query)
{
return em.createQuery(query).getResultList();
}
/*
* (non-Javadoc)
*
* @see com.impetus.core.KunderaEntity#query(java.lang.String,
* com.impetus.core.QueryType)
*/
public List query(String query, QueryType type)
{
switch (type)
{
case JPQL:
return query(query);
case NATIVE:
return nativeQuery(query);
default:
throw new KunderaException("invalid query type");
}
}
/**
* Native query.
*
* @param query
* the query
* @return the list
*/
private List nativeQuery(String query)
{
return em.createNativeQuery(query).getResultList();
}
}
================================================
FILE: src/data-as-object/src/main/java/com/impetus/core/KunderaEntity.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.core;
import java.util.List;
/**
* The Interface KunderaEntity.
*
* @param
* the generic type
* @param
* the key type
*/
public interface KunderaEntity
{
/**
* Find.
*
* @param key
* the key
* @return the t
*/
T find(K key);
/**
* Save.
*/
void save();
/**
* Update.
*/
void update();
/**
* Delete.
*/
void delete();
/**
* Query.
*
* @param query
* the query
* @return the list
*/
List query(String query);
/**
* Query.
*
* @param query
* the query
* @param type
* the type
* @return the list
*/
List query(String query, QueryType type);
/**
* Left join.
*
* @param clazz
* the clazz
* @param joinColumn
* the join column
* @param columnTobeFetched
* the column tobe fetched
* @return the list
*/
// List leftJoin(Class clazz, String joinColumn, String...
// columnTobeFetched);
}
================================================
FILE: src/data-as-object/src/main/java/com/impetus/core/PersistenceService.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.core;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.dao.utils.JsonUtil;
import com.impetus.dao.utils.PropertyReader;
import com.impetus.kundera.KunderaException;
/**
* The Class PersistenceService.
*/
public class PersistenceService
{
/** The logger. */
private static Logger LOGGER = LoggerFactory.getLogger(PersistenceService.class);
/**
* Gets the em.
*
* @param emf
* the emf
* @param propertiesPath
* the properties path
* @param clazzName
* the clazz name
* @return the em
*/
public static synchronized EntityManager getEM(EntityManagerFactory emf, final String propertiesPath,
final String clazzName)
{
/** The client properties. */
Map, Map> clientProperties = new HashMap<>();
/** The entity configurations. */
Map> entityConfigurations = Collections
.synchronizedMap(new HashMap>());
loadClientProperties(propertiesPath, clazzName, clientProperties, entityConfigurations);
if (emf == null)
{
StringBuilder puNames = new StringBuilder();
for (Entry> entry : entityConfigurations.entrySet())
{
if (entry.getValue().get("kundera.pu") != null)
{
puNames.append(entry.getValue().get("kundera.pu"));
puNames.append(",");
}
}
if (puNames.length() > 0)
{
puNames.deleteCharAt(puNames.length() - 1);
}
try
{
if (puNames.toString().isEmpty())
{
emf = Persistence.createEntityManagerFactory("testPU", entityConfigurations.get(clazzName));
}
else
{
emf = Persistence.createEntityManagerFactory(puNames.toString());
}
}
catch (Exception e)
{
LOGGER.error("Unable to create Entity Manager Factory. Caused By: ", e);
throw new KunderaException("Unable to create Entity Manager Factory. Caused By: ", e);
}
}
return emf.createEntityManager();
}
/**
* Load client properties.
*
* @param propertiesPath
* the properties path
* @param clazzName
* the clazz name
* @param clientProperties
* the client properties
* @param entityConfigurations
* the entity configurations
*/
private static void loadClientProperties(String propertiesPath, String clazzName,
Map, Map> clientProperties, Map> entityConfigurations)
{
InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(propertiesPath);
clientProperties = JsonUtil.readJson(inputStream, Map.class);
if (clientProperties != null)
{
if (clientProperties.get("all") != null)
{
entityConfigurations.put(clazzName, clientProperties.get("all"));
}
else
{
Iterator iter = clientProperties.keySet().iterator();
while (iter.hasNext())
{
Object key = iter.next();
if (((String) key).indexOf(',') > 0)
{
StringTokenizer tokenizer = new StringTokenizer((String) key, ",");
while (tokenizer.hasMoreElements())
{
String token = tokenizer.nextToken();
entityConfigurations.put(token, clientProperties.get(key));
}
}
else
{
entityConfigurations.put((String) key, clientProperties.get(key));
}
}
}
}
}
}
================================================
FILE: src/data-as-object/src/main/java/com/impetus/core/QueryType.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.core;
/**
* The Enum QueryType.
*/
public enum QueryType
{
/** The jpql. */
JPQL,
/** The native. */
NATIVE;
}
================================================
FILE: src/data-as-object/src/main/java/com/impetus/dao/utils/JsonUtil.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.dao.utils;
import java.io.IOException;
import java.io.InputStream;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.KunderaException;
/**
* The Class JsonUtil.
*/
public class JsonUtil
{
/** The logger. */
private static Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
/**
* Read json.
*
* @param
* the generic type
* @param json
* the json
* @param clazz
* the clazz
* @return the t
*/
public final static T readJson(String json, Class clazz)
{
ObjectMapper mapper = new ObjectMapper();
try
{
if (json != null && !json.isEmpty())
{
return mapper.readValue(json, clazz);
}
else
{
LOGGER.error("JSON is null or empty.");
throw new KunderaException("JSON is null or empty.");
}
}
catch (IOException e)
{
LOGGER.error("Error while converting in json{} presentation{}.", json, e);
throw new KunderaException("Error while mapping JSON to Object. Caused By: ", e);
}
}
/**
* Read json.
*
* @param
* the generic type
* @param jsonStream
* the json stream
* @param clazz
* the clazz
* @return the t
*/
public final static T readJson(InputStream jsonStream, Class clazz)
{
ObjectMapper mapper = new ObjectMapper();
try
{
if (jsonStream != null)
{
return mapper.readValue(jsonStream, clazz);
}
else
{
LOGGER.error("InputStream is null.");
throw new KunderaException("InputStream is null.");
}
}
catch (IOException e)
{
LOGGER.error("Error while mapping input stream to object. Caused By: ", e);
throw new KunderaException("Error while mapping input stream to object. Caused By: ", e);
}
}
}
================================================
FILE: src/data-as-object/src/main/java/com/impetus/dao/utils/PropertyReader.java
================================================
/*******************************************************************************
* * Copyright 2016 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.dao.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.KunderaException;
/**
* The Class PropertyReader.
*/
public class PropertyReader
{
/** The logger. */
private static Logger LOGGER = LoggerFactory.getLogger(PropertyReader.class);
/**
* Gets the props.
*
* @param fileName
* the file name
* @return the props
* @throws Exception
* the exception
*/
public static Properties getProps(String fileName) throws Exception
{
Properties properties = new Properties();
InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(fileName);
if (inputStream != null)
{
try
{
properties.load(inputStream);
}
catch (IOException e)
{
LOGGER.error("JSON is null or empty.");
throw new KunderaException("JSON is null or empty.");
}
}
else
{
throw new KunderaException("Property file: [" + fileName + "] not found in the classpath");
}
return properties;
}
}
================================================
FILE: src/data-as-object/src/main/resources/META-INF/persistence.xml
================================================
com.impetus.kundera.KunderaPersistence
================================================
FILE: src/jpa-engine/core/pom.xml
================================================
4.0.0
com.impetus.kundera.core
core-parent
3.14-SNAPSHOT
com.impetus.kundera.core
kundera-core
jar
kundera-core
http://maven.apache.org
junit
junit
4.8.2
test
directory-naming
naming-java
0.8
test
commons-lang
commons-lang
2.4
javax
javaee-api
7.0
org.eclipse.persistence
org.eclipse.persistence.jpa.jpql
2.5.2
cglib
cglib
2.2.2
commons-logging
commons-logging
1.1.1
org.slf4j
slf4j-api
1.7.5
org.javassist
javassist
3.21.0-GA
com.google.guava
guava
18.0
javax.transaction
jta
1.1
com.thoughtworks.xstream
xstream
1.4.3
commons-configuration
commons-configuration
1.9
com.vividsolutions
jts
1.11
xerces
xercesImpl
maven-assembly-plugin
2.2.1
jar-with-dependencies
org.apache.maven.plugins
maven-javadoc-plugin
2.8.1
private
true
org.apache.maven.plugins
maven-jar-plugin
2.2
test-jar
**/index/LuceneIndexer.class
**/persistence/EntityReaderTest.class
doclint-java8-disable
[1.8,)
org.apache.maven.plugins
maven-javadoc-plugin
-Xdoclint:none
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/Constants.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
/**
* Constants.
*
* @author animesh.kumar
* @since 0.1
*/
public interface Constants
{
/** The Constant ENCODING. */
public static final String ENCODING = "utf-8";
/** UTF-8 character set. */
public static final String CHARSET_UTF8 = "UTF-8";
/** The Constant SEPARATOR. */
public final static String FOREIGN_KEY_SEPARATOR = "~";
/** The Constant INVALID. */
public final static int INVALID = -1;
/** The Constant SUPER_COLUMN_NAME_DELIMITER. */
public final static String EMBEDDED_COLUMN_NAME_DELIMITER = "#";
/** The Constant TO_ONE_SUPER_COL_NAME. */
public static final String FOREIGN_KEY_EMBEDDED_COLUMN_NAME = "FKey-TO";
/** The Constant KUNDERA_SECONDARY_CACHE_NAME. */
public static final String KUNDERA_SECONDARY_CACHE_NAME = "Kundera";
/** The Constant PERSISTENCE_UNIT_NAME. */
public static final String PERSISTENCE_UNIT_NAME = "persistenceUnitName";
/** The Constant LUCENE_INDEX_DIRECTORY_NAME. */
public static final String LUCENE_INDEX_DIRECTORY_NAME = "lucene";
/**
* Separator used for providing persistence unit alongwith schema on entity
* class (applicable in case of cross-datastore persistence).
*/
public static final String SCHEMA_PERSISTENCE_UNIT_SEPARATOR = "@";
/**
* Separator used for providing a list of persistence units while creating
* EMF.
*/
public final static String PERSISTENCE_UNIT_SEPARATOR = ",";
/**
* Name of column family(HBase) or super column(cassandra) which houses all
* join columns.
*/
public final static String JOIN_COLUMNS_FAMILY_NAME = "JoinColumns";
/** The Constant JOIN_COLUMN_NAME_SEPARATOR. */
public final static String JOIN_COLUMN_NAME_SEPARATOR = "_";
/** The Constant NODE_ID_SEPARATOR. */
public final static String NODE_ID_SEPARATOR = "$";
/** The Constant RDBMS_CLIENT_FACTORY. */
public final static String RDBMS_CLIENT_FACTORY = "com.impetus.client.rdbms.RDBMSClientFactory";
/** The Constant NEO4J_CLIENT_FACTORY. */
public final static String NEO4J_CLIENT_FACTORY = "com.impetus.client.neo4j.Neo4JClientFactory";
/** The Constant REDIS_CLIENT_FACTORY. */
public final static String REDIS_CLIENT_FACTORY = "com.impetus.client.redis.RedisClientFactory";
/** The Constant DEFAULT_MAX_FETCH_DEPTH. */
public final static int DEFAULT_MAX_FETCH_DEPTH = 2;
/** The Constant INDEX_TABLE_SUFFIX. */
public final static String INDEX_TABLE_SUFFIX = "_INVRTD_IDX";
/** The Constant INDEX_TABLE_ROW_KEY_DELIMITER. */
public final static String INDEX_TABLE_ROW_KEY_DELIMITER = ".";
/** The Constant INDEX_TABLE_EC_DELIMITER. */
public final static String INDEX_TABLE_EC_DELIMITER = "@SuperColumn:";
/** The Constant LOADBALANCING_POLICY. */
public final static String LOADBALANCING_POLICY = "loadbalancing.policy";
/** The Constant FAILOVER_POLICY. */
public final static String FAILOVER_POLICY = "failover.policy";
/** The Constant FAIL_FAST. */
public final static String FAIL_FAST = "fail.fast";
/** The Constant ON_FAIL_TRY_ONE_NEXT_AVAILABLE. */
public final static String ON_FAIL_TRY_ONE_NEXT_AVAILABLE = "on.fail.try.one.next.available";
/** The Constant ON_FAIL_TRY_ALL_AVAILABLE. */
public final static String ON_FAIL_TRY_ALL_AVAILABLE = "on.fail.try.all.available";
/** The Constant RETRY_DELAY. */
public final static String RETRY_DELAY = "retry.delay";
/** The Constant RETRY. */
public final static String RETRY = "retry";
/** The Constant PERSISTENCE_UNIT_LOCATIION. */
public final static String PERSISTENCE_UNIT_LOCATIION = "persistenceunit.location";
/** The Constant DEFAULT_PERSISTENCE_UNIT_LOCATIION. */
public final static String DEFAULT_PERSISTENCE_UNIT_LOCATIION = "META-INF/persistence.xml";
/** The Constant SPACE. */
public final static String SPACE = " ";
/** The Constant DEFAULT_TIMESTAMP_GENERATOR. */
public final static String DEFAULT_TIMESTAMP_GENERATOR = "default.timestamp.generator";
/** The Constant AGGREGATIONS. */
public final static String AGGREGATIONS = "aggregations";
/** The Constant PRIMARY_KEYS. */
public final static String PRIMARY_KEYS = "primaryKeys";
/** The Constant SELECT_EXPRESSION_ORDER. */
public final static String SELECT_EXPRESSION_ORDER = "selectExpressionOrder";
/** The Constant COL_FAMILY. */
public static final String COL_FAMILY = "colFamily";
/** The Constant DB COL_NAME. */
public static final String DB_COL_NAME = "dbColumn";
/** The Constant COL_NAME. */
public static final String COL_NAME = "colName";
/** The Constant IGNORE_CASE. */
public static final String IGNORE_CASE = "ignoreCase";
/** The Constant COMPOSITE. */
public final static String COMPOSITE = "composite";
/** The Constant IS_EMBEDDABLE. */
public static final String IS_EMBEDDABLE = "isEmbeddable";
/** The Constant FIELD_CLAZZ. */
public static final String FIELD_CLAZZ = "fieldClazz";
/** The Constant FIELD_NAME. */
public static final String FIELD_NAME = "fieldName";
/** The Constant ESCAPE_QUOTE. */
public static final String ESCAPE_QUOTE = "\"";
/** The Constant OPEN_SQUARE_BRACKET. */
public static final String OPEN_SQUARE_BRACKET = "[";
/** The Constant CLOSE_SQUARE_BRACKET. */
public static final String CLOSE_SQUARE_BRACKET = "]";
/** The Constant OPEN_ROUND_BRACKET. */
public static final String OPEN_ROUND_BRACKET = "(";
/** The Constant CLOSE_ROUND_BRACKET. */
public static final String CLOSE_ROUND_BRACKET = ")";
/** The Constant OPEN_CURLY_BRACKET. */
public static final String OPEN_CURLY_BRACKET = "{";
/** The Constant COMMA. */
public static final String COMMA = ",";
/** The Constant CLOSE_CURLY_BRACKET. */
public static final String CLOSE_CURLY_BRACKET = "}";
/** The Constant COLON. */
public static final String COLON = ":";
/** The Constant SEMI_COLON. */
public static final String SEMI_COLON = ";";
/** The Constant STR_GT. */
public static final String STR_GT = ">";
/** The Constant STR_LT. */
public static final String STR_LT = "<";
/** The Constant SPACE_COMMA. */
public static final String SPACE_COMMA = " ,";
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/DataWrapper.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
/**
* The Interface DataWrapper.
*
* @author vivek.mishra
*/
public interface DataWrapper
{
/**
* Returns column family.
*
* @return column family.
*/
String getColumnFamily();
/**
* Returns row key.
*
* @return rowKey.
*/
byte[] getRowKey();
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaException.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
/**
* Base Exception class for all type of exceptions thrown by Kundera.
*
* @author amresh.singh
*/
public class KunderaException extends RuntimeException
{
private static final long serialVersionUID = 3855497974944993364L;
/**
*
*/
public KunderaException()
{
super();
}
/**
* @param arg0
*/
public KunderaException(String arg0)
{
super(arg0);
}
/**
* @param arg0
*/
public KunderaException(Throwable arg0)
{
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public KunderaException(String arg0, Throwable arg1)
{
super(arg0, arg1);
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaPersistence.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.ProviderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.configure.PersistenceUnitConfigurationException;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl;
/**
* The Class KunderaPersistence.
*
* @author animesh.kumar
*/
@SuppressWarnings("unchecked")
public class KunderaPersistence implements PersistenceProvider
{
/** The logger. */
private static Logger logger = LoggerFactory.getLogger(KunderaPersistence.class);
private final ProviderUtil providerUtil;
private final PersistenceUtilHelper.MetadataCache cache;
/**
* Instantiates a new kundera persistence.
*/
public KunderaPersistence()
{
this.providerUtil = new KunderaPersistenceProviderUtil(this);
this.cache = new PersistenceUtilHelper.MetadataCache();
}
@Override
public final EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map)
{
synchronized (this)
{
try
{
EntityManagerFactory emf = new EntityManagerFactoryImpl(info, map);
return emf;
}
catch (PersistenceUnitConfigurationException pcex)
{
// Means it is not for kundera persistence!
logger.error("EntityManagerFactory not created, returning null.");
return null;
}
}
}
@Override
public synchronized final EntityManagerFactory createEntityManagerFactory(String persistenceUnit, Map map)
{
// TODO: This may be a comma separated PU list, synchronizing on this
// list may not be intended
synchronized (this)
{
try
{
EntityManagerFactory emf = new EntityManagerFactoryImpl(persistenceUnit, map);
return emf;
}
catch (PersistenceUnitConfigurationException pcex)
{
// Means it is not for kundera persistence!
logger.error("EntityManagerFactory not created, returning null.");
return null;
}
}
}
/**
* Returns Persistence Provider util
*
* @see javax.persistence.spi.PersistenceProvider#getProviderUtil()
*/
@Override
public ProviderUtil getProviderUtil()
{
return this.providerUtil;
}
/**
* @return the cache
*/
public PersistenceUtilHelper.MetadataCache getCache()
{
return cache;
}
@Override
public void generateSchema(PersistenceUnitInfo arg0, Map arg1)
{
//TODO: See https://github.com/impetus-opensource/Kundera/issues/457
// do nothing.
}
@Override
public boolean generateSchema(String arg0, Map arg1)
{
// returning default.
return false;
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaPersistenceProviderUtil.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera;
import javax.persistence.spi.LoadState;
import javax.persistence.spi.ProviderUtil;
/**
* {@link ProviderUtil} for {@link KunderaPersistence}
*
* @author amresh.singh
*/
public class KunderaPersistenceProviderUtil implements ProviderUtil
{
KunderaPersistence provider;
public KunderaPersistenceProviderUtil(KunderaPersistence provider)
{
this.provider = provider;
}
/**
* If the provider determines that the entity has been provided by itself
* and that the state of the specified attribute has been loaded, this
* method returns LoadState.LOADED. If the provider determines that the
* entity has been provided by itself and that either entity attributes with
* FetchType EAGER have not been loaded or that the state of the specified
* attribute has not been loaded, this methods returns LoadState.NOT_LOADED.
* If a provider cannot determine the load state, this method returns
* LoadState.UNKNOWN. The provider's implementation of this method must not
* obtain a reference to an attribute value, as this could trigger the
* loading of entity state if the entity has been provided by a different
* provider.
*
* @param entity
* @param attributeName
* name of attribute whose load status is to be determined
* @return load status of the attribute
*/
@Override
public LoadState isLoadedWithoutReference(Object paramObject, String paramString)
{
return PersistenceUtilHelper.isLoadedWithoutReference(paramObject, paramString, provider.getCache());
}
/**
* If the provider determines that the entity has been provided by itself
* and that the state of the specified attribute has been loaded, this
* method returns LoadState.LOADED. If a provider determines that the entity
* has been provided by itself and that either the entity attributes with
* FetchType EAGER have not been loaded or that the state of the specified
* attribute has not been loaded, this method returns LoadState.NOT_LOADED.
* If the provider cannot determine the load state, this method returns
* LoadState.UNKNOWN. The provider's implementation of this method is
* permitted to obtain a reference to the attribute value. (This access is
* safe because providers which might trigger the loading of the attribute
* state will have already been determined by isLoadedWithoutReference. )
*
* @param entity
* @param attributeName
* name of attribute whose load status is to be determined
* @return load status of the attribute
*/
@Override
public LoadState isLoadedWithReference(Object paramObject, String paramString)
{
return PersistenceUtilHelper.isLoadedWithReference(paramObject, paramString, provider.getCache());
}
/**
* If the provider determines that the entity has been provided by itself
* and that the state of all attributes for which FetchType EAGER has been
* specified have been loaded, this method returns LoadState.LOADED. If the
* provider determines that the entity has been provided by itself and that
* not all attributes with FetchType EAGER have been loaded, this method
* returns LoadState.NOT_LOADED. If the provider cannot determine if the
* entity has been provided by itself, this method returns
* LoadState.UNKNOWN. The provider's implementation of this method must not
* obtain a reference to any attribute value, as this could trigger the
* loading of entity state if the entity has been provided by a different
* provider.
*
* @param entity
* whose loaded status is to be determined
* @return load status of the entity
*/
@Override
public LoadState isLoaded(Object paramObject)
{
return PersistenceUtilHelper.isLoaded(paramObject);
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaPersistenceUnitUtil.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.spi.LoadState;
import com.impetus.kundera.property.PropertyAccessorHelper;
/**
* {@link PersistenceUnitUtil} for {@link KunderaPersistence}
*
* @author amresh.singh
*/
public class KunderaPersistenceUnitUtil implements PersistenceUnitUtil
{
private transient PersistenceUtilHelper.MetadataCache cache;
public KunderaPersistenceUnitUtil(PersistenceUtilHelper.MetadataCache cache)
{
this.cache = cache;
}
@Override
public boolean isLoaded(Object entity, String attributeName)
{
LoadState state = PersistenceUtilHelper.isLoadedWithoutReference(entity, attributeName, this.cache);
if (state == LoadState.LOADED)
{
return true;
}
if (state == LoadState.NOT_LOADED)
{
return false;
}
return (PersistenceUtilHelper.isLoadedWithReference(entity, attributeName, this.cache) != LoadState.NOT_LOADED);
}
@Override
public boolean isLoaded(Object entity)
{
return (PersistenceUtilHelper.isLoaded(entity) != LoadState.NOT_LOADED);
}
@Override
public Object getIdentifier(Object entity)
{
Class> entityClass = entity.getClass();
// EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
//
// if (entityMetadata == null)
// {
// throw new IllegalArgumentException(entityClass + " is not an entity");
// }
return PropertyAccessorHelper.getId(entity, /*entityMetadata*/null);
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/PersistenceProperties.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera;
/**
* Contains all constants properties supported in persistence.xml
*
* @author amresh.singh
*
*/
public interface PersistenceProperties
{
/** The Constant KUNDERA_NODES. */
public static final String KUNDERA_NODES = "kundera.nodes";
/** The Constant KUNDERA_PORT. */
public static final String KUNDERA_PORT = "kundera.port";
/** The Constant KUNDERA_KEYSPACE. */
public static final String KUNDERA_KEYSPACE = "kundera.keyspace";
/** The Constant KUNDERA_DIALECT. */
public static final String KUNDERA_DIALECT = "kundera.dialect";
/** The Constant Kundera Client factory */
public static final String KUNDERA_CLIENT_FACTORY = "kundera.client.lookup.class";
/** The Constant KUNDERA_CACHE_PROVIDER_CLASS. */
public static final String KUNDERA_CACHE_PROVIDER_CLASS = "kundera.cache.provider.class";
/** The Constant KUNDERA_CACHE_CONFIG_RESOURCE. */
public static final String KUNDERA_CACHE_CONFIG_RESOURCE = "kundera.cache.config.resource";
/** The Constant KUNDERA_FETCH_MAX_DEPTH. */
public static final String KUNDERA_FETCH_MAX_DEPTH = "kundera.fetch.max.depth";
/** Connection Pooling related constants. */
// Cap on the number of object instances managed by the pool per node.
public static final String KUNDERA_POOL_SIZE_MAX_ACTIVE = "kundera.pool.size.max.active";
// Cap on the number of "idle" instances in the pool.
/** The Constant KUNDERA_POOL_SIZE_MAX_IDLE. */
public static final String KUNDERA_POOL_SIZE_MAX_IDLE = "kundera.pool.size.max.idle";
// Minimum number of idle objects to maintain in each of the nodes.
/** The Constant KUNDERA_POOL_SIZE_MIN_IDLE. */
public static final String KUNDERA_POOL_SIZE_MIN_IDLE = "kundera.pool.size.min.idle";
// Cap on the total number of instances from all nodes combined.
/** The Constant KUNDERA_POOL_SIZE_MAX_TOTAL. */
public static final String KUNDERA_POOL_SIZE_MAX_TOTAL = "kundera.pool.size.max.total";
/**
* Home directory for alternative secondary indexing, Lucene to be specific.
*/
public static final String KUNDERA_INDEX_HOME_DIR = "index.home.dir";
/** Option to create schema. */
public static final String KUNDERA_DDL_AUTO_PREPARE = "kundera.ddl.auto.prepare";
public static final String KUNDERA_SHOW_QUERY="kundera.show.query";
/** Option to give kundera-cassandra property information */
public static final String KUNDERA_CLIENT_PROPERTY = "kundera.client.property";
public static final String KUNDERA_USERNAME = "kundera.username";
public static final String KUNDERA_PASSWORD = "kundera.password";
public static final String KUNDERA_BATCH_SIZE = "kundera.batch.size";
public static final String KUNDERA_TRANSACTION_TIMEOUT = "kundera.transaction.timeout";
/** Location where datastore file is stored */
public static final String KUNDERA_DATASTORE_FILE_PATH = "kundera.datastore.file.path";
public static final String KUNDERA_TRANSACTION_RESOURCE = "kundera.transaction.resource.class";
public static final String KUNDERA_INDEXER_CLASS = "kundera.indexer.class";
public static final String KUNDERA_AUTO_GENERATOR_CLASS = "kundera.auto.generator.class";
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/PersistenceUtilHelper.java
================================================
/**
* Copyright 2012 Impetus Infotech.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.impetus.kundera;
import java.io.Serializable;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.persistence.PersistenceException;
import javax.persistence.PersistenceUtil;
import javax.persistence.spi.LoadState;
import com.impetus.kundera.proxy.KunderaProxy;
import com.impetus.kundera.proxy.LazyInitializer;
import com.impetus.kundera.proxy.ProxyHelper;
import com.impetus.kundera.proxy.collection.AbstractProxyCollection;
/**
* Helper for {@link PersistenceUtil}
*/
public class PersistenceUtilHelper
{
public static LoadState isLoadedWithReference(Object proxy, String property, MetadataCache cache)
{
return proxy == null? LoadState.NOT_LOADED:isLoaded(get(proxy, property, cache));
}
public static LoadState isLoadedWithoutReference(Object proxy, String property, MetadataCache cache)
{
if (proxy == null || property == null)
{
return LoadState.NOT_LOADED;
}
if (proxy instanceof KunderaProxy)
{
LazyInitializer li = ((KunderaProxy) proxy).getKunderaLazyInitializer();
if (li.isUninitialized())
{
return LoadState.NOT_LOADED;
}
return LoadState.LOADED;
}
else
{
return LoadState.LOADED;
}
}
private static Object get(Object proxy, String property, MetadataCache cache)
{
final Class> clazz = proxy.getClass();
try
{
Member member = cache.getMember(clazz, property);
if (member instanceof Field)
{
return ((Field) member).get(proxy);
}
else if (member instanceof Method)
{
return ((Method) member).invoke(proxy);
}
else
{
throw new PersistenceException("Member object neither Field nor Method: " + member);
}
}
catch (IllegalAccessException e)
{
throw new PersistenceException("Unable to access field or method: " + clazz + "#" + property, e);
}
catch (InvocationTargetException e)
{
throw new PersistenceException("Unable to access field or method: " + clazz + "#" + property, e);
}
}
private static void setAccessibility(Member member)
{
((AccessibleObject) member).setAccessible(true);
}
public static LoadState isLoaded(Object o)
{
if (o == null)
{
return LoadState.NOT_LOADED;
}
else if (o instanceof KunderaProxy)
{
final boolean isInitialized = !((KunderaProxy) o).getKunderaLazyInitializer().isUninitialized();
return isInitialized ? LoadState.LOADED : LoadState.NOT_LOADED;
}
else if(ProxyHelper.isKunderaProxyCollection(o))
{
final boolean isInitialized = ((AbstractProxyCollection) o).getDataCollection() != null;
return isInitialized ? LoadState.LOADED : LoadState.NOT_LOADED;
}
else
{
return LoadState.UNKNOWN;
}
}
/**
* Returns the method with the specified name or null if it
* does not exist.
*
* @param clazz
* The class to check.
* @param methodName
* The method name.
*
* @return Returns the method with the specified name or null
* if it does not exist.
*/
private static Method getMethod(Class> clazz, String methodName)
{
try
{
char string[] = methodName.toCharArray();
string[0] = Character.toUpperCase(string[0]);
methodName = new String(string);
try
{
return clazz.getDeclaredMethod("get" + methodName);
}
catch (NoSuchMethodException e)
{
return clazz.getDeclaredMethod("is" + methodName);
}
}
catch (NoSuchMethodException e)
{
return null;
}
}
/**
* Cache hierarchy and member resolution in a weak hash map
*/
public static class MetadataCache implements Serializable
{
private transient Map, ClassCache> classCache = new WeakHashMap, ClassCache>();
private void readObject(java.io.ObjectInputStream stream)
{
classCache = new WeakHashMap, ClassCache>();
}
Member getMember(Class> clazz, String property)
{
ClassCache cache = classCache.get(clazz);
if (cache == null)
{
cache = new ClassCache(clazz);
classCache.put(clazz, cache);
}
Member member = cache.members.get(property);
if (member == null)
{
member = findMember(clazz, property);
cache.members.put(property, member);
}
return member;
}
private Member findMember(Class> clazz, String property)
{
final List> classes = getClassHierarchy(clazz);
for (Class current : classes)
{
final Field field;
try
{
field = current.getDeclaredField(property);
setAccessibility(field);
return field;
}
catch (NoSuchFieldException e)
{
final Method method = getMethod(current, property);
if (method != null)
{
setAccessibility(method);
return method;
}
}
}
// we could not find any match
throw new PersistenceException("Unable to find field or method: " + clazz + "#" + property);
}
private List> getClassHierarchy(Class> clazz)
{
ClassCache cache = classCache.get(clazz);
if (cache == null)
{
cache = new ClassCache(clazz);
classCache.put(clazz, cache);
}
return cache.classHierarchy;
}
private static List> findClassHierarchy(Class> clazz)
{
List> classes = new ArrayList>();
Class> current = clazz;
do
{
classes.add(current);
current = current.getSuperclass();
}
while (current != null);
return classes;
}
private static class ClassCache
{
List> classHierarchy;
Map members = new HashMap();
public ClassCache(Class> clazz)
{
classHierarchy = findClassHierarchy(clazz);
}
}
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/Cache.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.cache;
/**
* Implementors define a caching algorithm. All implementors must be
* threadsafe.
*
* @author animesh.kumar
*/
public interface Cache extends javax.persistence.Cache
{
/**
* Size.
*
* @return the int
*/
int size();
/**
* Get an item from the cache.
*
* @param key
* the key
* @return the object
*/
Object get(Object key);
/**
* Add an item to the cache.
*
* @param key
* the key
* @param value
* the value
*/
void put(Object key, Object value);
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/CacheException.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.cache;
import com.impetus.kundera.KunderaException;
/**
* When something goes wrong in cache.
*
* @author animesh.kumar
*
*/
public class CacheException extends KunderaException
{
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new cache exception.
*
* @param s
* the s
*/
public CacheException(final String s)
{
super(s);
}
/**
* Instantiates a new cache exception.
*
* @param s
* the s
* @param e
* the e
*/
public CacheException(final String s, final Throwable e)
{
super(s, e);
}
/**
* Instantiates a new cache exception.
*
* @param e
* the e
*/
public CacheException(final Throwable e)
{
super(e);
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/CacheProvider.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.cache;
import java.util.Map;
import javax.persistence.Cache;
/**
* CacheProvider.
*
* @author animesh.kumar
*/
public interface CacheProvider
{
/**
* Called once to load up the CacheManager.
*
* @param properties
* the properties
* @throws CacheException
* the cache exception
*/
void init(Map, ?> properties);
/**
* Inits the.
*
* @param cacheResourceName
* the cache resource name
* @throws CacheException
* the cache exception
*/
void init(String cacheResourceName);
/**
* Creates cache for a given name.
*
* @param name
* the name
* @return the cache
* @throws CacheException
* the cache exception
*/
Cache createCache(String name);
/**
* Returns cache for a given cache name.
*
* @param name
* Cache Name
* @return the cache
* @throws CacheException
* the cache exception
*/
Cache getCache(String name);
/**
* Shutdown cache.
*/
void shutdown();
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/ElementCollectionCacheManager.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.cache;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.Constants;
import com.impetus.kundera.utils.DeepEquals;
/**
* Cache for holding element collection column names and corresponding objects
* This is a singleton class TODO: Improve singleton implementation code, think
* performance overhead due to synchronization TODO: Think of a better way to
* handle element collection object handling. better remove this cache
* altogether
*
* @author amresh.singh
*/
public class ElementCollectionCacheManager
{
/** log for this class. */
private static Logger log = LoggerFactory.getLogger(ElementCollectionCacheManager.class);
/* Single instance */
/** The instance. */
private static ElementCollectionCacheManager instance;
/**
* Instantiates a new element collection cache manager.
*/
private ElementCollectionCacheManager()
{
}
/**
* Gets the single instance of ElementCollectionCacheManager.
*
* @return single instance of ElementCollectionCacheManager
*/
public static synchronized ElementCollectionCacheManager getInstance()
{
if (instance == null)
{
instance = new ElementCollectionCacheManager();
}
return instance;
}
/**
* Mapping between Row Key and (Map of element collection objects and
* element collection object name).
*/
private static Map> elementCollectionCache;
/**
* Gets the element collection cache.
*
* @return the elementCollectionCache
*/
public Map> getElementCollectionCache()
{
if (this.elementCollectionCache == null)
{
this.elementCollectionCache = new HashMap>();
}
return this.elementCollectionCache;
}
/**
* Checks if is cache empty.
*
* @return true, if is cache empty
*/
public boolean isCacheEmpty()
{
return elementCollectionCache == null || elementCollectionCache.isEmpty();
}
/**
* Adds the element collection cache mapping.
*
* @param rowKey
* the row key
* @param elementCollectionObject
* the element collection object
* @param elementCollObjectName
* the element coll object name
*/
public void addElementCollectionCacheMapping(Object rowKey, Object elementCollectionObject,
String elementCollObjectName)
{
Map embeddedObjectMap = new HashMap();
if (getElementCollectionCache().get(rowKey) == null)
{
embeddedObjectMap.put(elementCollectionObject, elementCollObjectName);
getElementCollectionCache().put(rowKey, embeddedObjectMap);
}
else
{
getElementCollectionCache().get(rowKey).put(elementCollectionObject, elementCollObjectName);
}
}
/**
* Gets the element collection object name.
*
* @param rowKey
* the row key
* @param elementCollectionObject
* the element collection object
* @return the element collection object name
*/
public String getElementCollectionObjectName(Object rowKey, Object elementCollectionObject)
{
if (getElementCollectionCache().isEmpty() || getElementCollectionCache().get(rowKey) == null)
{
log.debug("No element collection object map found in cache for Row key " + rowKey);
return null;
}
else
{
Map elementCollectionObjectMap = getElementCollectionCache().get(rowKey);
String elementCollectionObjectName = elementCollectionObjectMap.get(elementCollectionObject);
if (elementCollectionObjectName == null)
{
for (Object obj : elementCollectionObjectMap.keySet())
{
if (DeepEquals.deepEquals(elementCollectionObject, obj))
{
elementCollectionObjectName = elementCollectionObjectMap.get(obj);
break;
}
}
}
if (elementCollectionObjectName == null)
{
log.debug("No element collection object name found in cache for object:" + elementCollectionObject);
return null;
}
else
{
return elementCollectionObjectName;
}
}
}
/**
* Gets the last element collection object count.
*
* @param rowKey
* the row key
* @return the last element collection object count
*/
public int getLastElementCollectionObjectCount(Object rowKey)
{
if (getElementCollectionCache().get(rowKey) == null)
{
log.debug("No element collection object map found in cache for Row key " + rowKey);
return -1;
}
else
{
Map elementCollectionMap = getElementCollectionCache().get(rowKey);
Collection elementCollectionObjectNames = elementCollectionMap.values();
int max = 0;
for (String s : elementCollectionObjectNames)
{
String elementCollectionCountStr = s.substring(s.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) + 1);
int elementCollectionCount = 0;
try
{
elementCollectionCount = Integer.parseInt(elementCollectionCountStr);
}
catch (NumberFormatException e)
{
log.error("Invalid element collection Object name " + s);
throw new CacheException("Invalid element collection Object name " + s,e);
}
if (elementCollectionCount > max)
{
max = elementCollectionCount;
}
}
return max;
}
}
/**
* Clear cache.
*/
public void clearCache()
{
this.elementCollectionCache = null;
try
{
finalize();
}
catch (Throwable e)
{
log.warn("Unable to reclaim memory while clearing ElementCollection cache. Nothing to worry, will be taken care of by GC");
}
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/NonOperationalCache.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.cache;
/**
* NonOperational Cache implementation.
*
* @author animesh.kumar
*
*/
public class NonOperationalCache implements Cache, javax.persistence.Cache
{
/* @see com.impetus.kundera.cache.Cache#size() */
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.cache.Cache#size()
*/
@Override
public int size()
{
return 0;
}
/*
* @see com.impetus.kundera.cache.Cache#put(java.lang.Object,
* java.lang.Object)
*/
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.cache.Cache#put(java.lang.Object,
* java.lang.Object)
*/
@Override
public void put(final Object key, final Object value)
{
}
/* @see com.impetus.kundera.cache.Cache#get(java.lang.Object) */
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.cache.Cache#get(java.lang.Object)
*/
@Override
public Object get(final Object key)
{
return null;
}
/*
* (non-Javadoc)
*
* @see javax.persistence.Cache#contains(java.lang.Class, java.lang.Object)
*/
@Override
public boolean contains(Class paramClass, Object paramObject)
{
return false;
}
/*
* (non-Javadoc)
*
* @see javax.persistence.Cache#evict(java.lang.Class, java.lang.Object)
*/
@Override
public void evict(Class paramClass, Object paramObject)
{
//TODO: See https://github.com/impetus-opensource/Kundera/issues/457
// do nothing.
}
/*
* (non-Javadoc)
*
* @see javax.persistence.Cache#evict(java.lang.Class)
*/
@Override
public void evict(Class paramClass)
{
//TODO: See https://github.com/impetus-opensource/Kundera/issues/457
// do nothing.
}
/*
* (non-Javadoc)
*
* @see javax.persistence.Cache#evictAll()
*/
@Override
public void evictAll()
{
//TODO: See https://github.com/impetus-opensource/Kundera/issues/457
// do nothing.
}
@Override
public T unwrap(Class arg0)
{
//TODO: See https://github.com/impetus-opensource/Kundera/issues/457
// do nothing.
return null;
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/NonOperationalCacheProvider.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.cache;
import java.util.Map;
import javax.persistence.Cache;
/**
* NonOperational cache provider.
*
* @author animesh.kumar
*/
public class NonOperationalCacheProvider implements CacheProvider
{
/** The cache. */
private Cache cache = new NonOperationalCache();
/**
* Instantiates a new non operational cache provider.
*/
public NonOperationalCacheProvider()
{
}
/* @see com.impetus.kundera.cache.CacheProvider#init(java.util.Map) */
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.cache.CacheProvider#init(java.util.Map)
*/
@Override
public void init(Map, ?> properties)
{
}
/*
* @see
* com.impetus.kundera.cache.CacheProvider#createCache(java.lang.String)
*/
/*
* (non-Javadoc)
*
* @see
* com.impetus.kundera.cache.CacheProvider#createCache(java.lang.String)
*/
@Override
public Cache createCache(String name)
{
return cache;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.cache.CacheProvider#getCache(java.lang.String)
*/
@Override
public Cache getCache(String name) throws CacheException
{
return null;
}
/* @see com.impetus.kundera.cache.CacheProvider#shutdown() */
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.cache.CacheProvider#shutdown()
*/
@Override
public void shutdown()
{
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.cache.CacheProvider#init(java.lang.String)
*/
@Override
public void init(String cacheResourceName) throws CacheException
{
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/AnnotationDiscoveryListener.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
/**
* The Interface AnnotationDiscoveryListener.
*
* @author animesh.kumar
*/
public interface AnnotationDiscoveryListener
{
/**
* Discovered.
*
* @param className
* the class name
*/
void discovered(String className);
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ClassFileIterator.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* The Class ClassFileIterator.
*
* @author animesh.kumar
*/
public class ClassFileIterator implements ResourceIterator
{
/** The files. */
private List files;
/** The index. */
private int index = 0;
/**
* Instantiates a new class file iterator.
*
* @param file
* the file
* @param filter
* the filter
*/
public ClassFileIterator(File file, Filter filter)
{
files = new ArrayList();
init(files, file, filter);
}
/**
* Instantiates a new class file iterator.
*
* @param fileToAdd
* the file to add
*/
public ClassFileIterator(File fileToAdd)
{
files = new ArrayList();
files.add(fileToAdd);
}
/**
* Creates the.
*
* @param list
* the list
* @param dir
* the dir
* @param filter
* the filter
*
* @throws Exception
* the exception
*/
private static void init(List list, File dir, Filter filter)
{
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++)
{
if (files[i].isDirectory())
{
init(list, files[i], filter);
}
else
{
if (filter == null || filter.accepts(files[i].getAbsolutePath()))
{
list.add(files[i]);
}
}
}
}
public final InputStream next()
{
if (index >= files.size())
return null;
File fp = (File) files.get(index++);
try
{
return new FileInputStream(fp);
}
catch (FileNotFoundException e)
{
throw new ResourceReadingException("Couldn't read file " + fp, e);
}
}
public void close()
{
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ClasspathReader.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.impetus.kundera.Constants;
import com.impetus.kundera.loader.PersistenceXMLLoader.AllowedProtocol;
/**
* The Class ClasspathReader.
*
* @author animesh.kumar
*/
public class ClasspathReader extends Reader
{
private static Logger logger = LoggerFactory.getLogger(ClasspathReader.class);
/**
* The filter.
*/
private Filter filter;
/** The classes to scan. */
private List classesToScan;
/**
* Instantiates a new classpath reader.
*/
public ClasspathReader()
{
filter = new FilterImpl();
}
/**
* Instantiates a new classpath reader.
*
* @param classesToScan
* the classes to scan
*/
public ClasspathReader(List classesToScan)
{
this();
this.classesToScan = classesToScan;
}
@Override
public final void read()
{
URL[] resources = findResources();
for (URL resource : resources)
{
try
{
ResourceIterator itr = getResourceIterator(resource, getFilter());
InputStream is = null;
while ((is = itr.next()) != null)
{
scanClass(is);
}
}
catch (IOException e)
{
logger.error("Error during reading via classpath, Caused by:" + e.getMessage());
throw new ResourceReadingException(e);
}
}
}
/**
* Uses the java.class.path system property to obtain a list of URLs that
* represent the CLASSPATH
*
* @return the URl[]
*/
@SuppressWarnings("deprecation")
@Override
public final URL[] findResourcesByClasspath()
{
List list = new ArrayList();
String classpath = System.getProperty("java.class.path");
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens())
{
String path = tokenizer.nextToken();
File fp = new File(path);
if (!fp.exists())
throw new ResourceReadingException("File in java.class.path does not exist: " + fp);
try
{
list.add(fp.toURL());
}
catch (MalformedURLException e)
{
throw new ResourceReadingException(e);
}
}
return list.toArray(new URL[list.size()]);
}
/**
* Scan class resource in the provided urls with the additional Class-Path
* of each jar checking
*
* @param classRelativePath
* relative path to a class resource
* @param urls
* urls to be checked
* @return list of class path included in the base package
*/
private URL[] findResourcesInUrls(String classRelativePath, URL[] urls)
{
List list = new ArrayList();
for (URL url : urls)
{
if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase()) && url.getPath().endsWith(".jar"))
{
try
{
JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8));
// Checking the dependencies of this jar file
Manifest manifest = jarFile.getManifest();
if (manifest != null)
{
String classPath = manifest.getMainAttributes().getValue("Class-Path");
// Scan all entries in the classpath if they are
// specified in the jar
if (!StringUtils.isEmpty(classPath))
{
List subList = new ArrayList();
for (String cpEntry : classPath.split(" "))
{
try
{
subList.add(new URL(cpEntry));
}
catch (MalformedURLException e)
{
URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry);
if (subResources != null)
{
subList.add(subResources);
}
// logger.warn("Incorrect URL in the classpath of a jar file ["
// + url.toString()
// + "]: " + cpEntry);
}
}
list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath,
subList.toArray(new URL[subList.size()]))));
}
}
JarEntry present = jarFile.getJarEntry(classRelativePath + ".class");
if (present != null)
{
list.add(url);
}
}
catch (IOException e)
{
logger.warn("Error during loading from context , Caused by:" + e.getMessage());
}
}
else if (url.getPath().endsWith("/"))
{
File file = new File(url.getPath() + classRelativePath + ".class");
if (file.exists())
{
try
{
list.add(file.toURL());
}
catch (MalformedURLException e)
{
throw new ResourceReadingException(e);
}
}
}
}
return list.toArray(new URL[list.size()]);
}
/**
* Scan class resources into a basePackagetoScan path.
*
* @return list of class path included in the base package
*/
private final URL[] findResourcesByContextLoader()
{
List list = new ArrayList();
ClassLoader classLoader = this.getClass().getClassLoader();
assert classLoader != null;
URL[] urls = ((URLClassLoader) classLoader).getURLs();
for (String fullyQualifiedClassName : classesToScan)
{
String classRelativePath = fullyQualifiedClassName.replace(".", "/");
list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath, urls)));
}
return list.toArray(new URL[list.size()]);
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.classreading.Reader#findResources()
*/
@Override
public URL[] findResources()
{
URL[] result = null;
if (classesToScan != null && !classesToScan.isEmpty())
{
result = findResourcesByContextLoader();
}
// else
// {
// result = findResourcesByClasspath();
// }
return result;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.classreading.Reader#getFilter()
*/
public final Filter getFilter()
{
return filter;
}
/**
* Sets the filter.
*
* @param filter
* the new filter
*/
public final void setFilter(Filter filter)
{
this.filter = filter;
}
@Override
public InputStream[] findResourcesAsStream()
{
ClassLoader classLoader = this.getClass().getClassLoader();
assert classLoader != null;
InputStream[] iStreams = null;
int counter = 0;
if(classesToScan != null)
{
for (String fullyQualifiedClassName : classesToScan)
{
if (iStreams == null)
{
iStreams = new InputStream[classesToScan.size()];
}
String classRelativePath = fullyQualifiedClassName.replace(".", "/");
InputStream is = this.getClass().getClassLoader().getResourceAsStream(classRelativePath + ".class");
iStreams[counter++] = is;
}
}
return iStreams;
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/Filter.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
/**
* Interface to filter out filenames.
*
* @author animesh.kumar
*/
public interface Filter
{
/**
* Accepts.
*
* @param filename
* the filename
*
* @return true, if successful
*/
boolean accepts(String filename);
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/FilterImpl.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
/**
* Basic implementation to skip well-known packages and allow only *.class files
*
* @author animesh.kumar
*/
public class FilterImpl implements Filter
{
/** The ignored packages. */
private transient String[] ignoredPackages = { "javax", "java", "sun", "com.sun", "javassist" };
/* @see com.impetus.kundera.classreading.Filter#accepts(java.lang.String) */
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.classreading.Filter#accepts(java.lang.String)
*/
@Override
public final boolean accepts(String filename)
{
if (filename.endsWith(".class"))
{
if (filename.startsWith("/"))
{
filename = filename.substring(1);
}
if (!ignoreScan(filename.replace('/', '.')))
{
return true;
}
}
return false;
}
/**
* Ignore scan.
*
* @param intf
* the intf
*
* @return true, if successful
*/
private boolean ignoreScan(String intf)
{
for (String ignored : ignoredPackages)
{
if (intf.startsWith(ignored + "."))
{
return true;
}
}
return false;
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/JarFileIterator.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
/**
* Iterates through a Jar file for each file resource.
*
* @author animesh.kumar
*/
public final class JarFileIterator implements ResourceIterator
{
/** The jar. */
private JarInputStream jar;
/** The next. */
private JarEntry next;
/** The filter. */
private Filter filter;
/** The initial. */
private boolean initial = true;
/** The closed. */
private boolean closed = false;
/**
* Instantiates a new jar file iterator.
*
* @param file
* the file
* @param filter
* the filter
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
/*
* public JarFileIterator(File file, Filter filter) throws
* FileNotFoundException { this(new FileInputStream(file), filter); }
*/
/**
* Instantiates a new jar file iterator.
*
* @param is
* the is
* @param filter
* the filter
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public JarFileIterator(InputStream is, Filter filter)
{
this.filter = filter;
try
{
jar = new JarInputStream(is);
}
catch (IOException e)
{
throw new ResourceReadingException(e);
}
}
/**
* Sets the next.
*/
private void setNext()
{
initial = true;
try
{
if (next != null)
{
jar.closeEntry();
}
next = null;
do
{
next = jar.getNextJarEntry();
}
while (next != null && (next.isDirectory() || (filter == null || !filter.accepts(next.getName()))));
if (next == null)
{
close();
}
}
catch (IOException e)
{
throw new ResourceReadingException("Failed to browse jar:", e);
}
}
public InputStream next()
{
if (closed || (next == null && !initial))
return null;
setNext();
if (next == null)
return null;
return new InputStreamWrapper(jar);
}
public void close()
{
try
{
closed = true;
jar.close();
}
catch (IOException ignored)
{
}
}
/**
* The Class InputStreamWrapper.
*/
class InputStreamWrapper extends InputStream
{
/** The delegate. */
private InputStream delegate;
/**
* Instantiates a new input stream wrapper.
*
* @param delegate
* the delegate
*/
public InputStreamWrapper(InputStream delegate)
{
this.delegate = delegate;
}
public int read() throws IOException
{
return delegate.read();
}
public int read(byte[] bytes) throws IOException
{
return delegate.read(bytes);
}
public int read(byte[] bytes, int i, int i1) throws IOException
{
return delegate.read(bytes, i, i1);
}
public long skip(long l) throws IOException
{
return delegate.skip(l);
}
public int available() throws IOException
{
return delegate.available();
}
public void close() throws IOException
{
// ignored
}
public void mark(int i)
{
delegate.mark(i);
}
public void reset() throws IOException
{
try
{
delegate.reset();
}
catch (IOException e)
{
throw e;
}
}
public boolean markSupported()
{
return delegate.markSupported();
}
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/Reader.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.annotation.Annotation;
import com.impetus.kundera.loader.PersistenceXMLLoader.AllowedProtocol;
/**
* Base class-reader.
*
* @author animesh.kumar
*/
public abstract class Reader
{
/** The valid annotations. */
private List validAnnotations = new ArrayList();
/** The annotation discovery listeners. */
private List annotationDiscoveryListeners = new ArrayList();
/**
* Instantiates a new reader.
*/
public Reader()
{
}
/**
* Scan class.
*
* @param bits
* the bits
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public void scanClass(InputStream bits) throws IOException
{
DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
ClassFile cf = null;
try
{
cf = new ClassFile(dstream);
String className = cf.getName();
List annotations = new ArrayList();
accumulateAnnotations(annotations, (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag));
accumulateAnnotations(annotations,
(AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag));
// iterate through all valid annotations
for (String validAnn : getValidAnnotations())
{
// check if the current class has one?
if (annotations.contains(validAnn))
{
// fire all listeners
for (AnnotationDiscoveryListener listener : getAnnotationDiscoveryListeners())
{
listener.discovered(className);
}
}
}
}
finally
{
dstream.close();
bits.close();
}
}
// helper method to accumulate annotations.
/**
* Accumulate annotations.
*
* @param annotations
* the annotations
* @param annatt
* the annatt
*/
public void accumulateAnnotations(List annotations, AnnotationsAttribute annatt)
{
if (null == annatt)
{
return;
}
for (Annotation ann : annatt.getAnnotations())
{
annotations.add(ann.getTypeName());
}
}
/**
* Gets the resource iterator.
*
* @param url
* the url
* @param filter
* the filter
*
* @return the resource iterator
*
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public ResourceIterator getResourceIterator(URL url, Filter filter)
{
String urlString = url.toString();
try
{
if (urlString.endsWith("!/"))
{
urlString = urlString.substring(4);
urlString = urlString.substring(0, urlString.length() - 2);
url = new URL(urlString);
}
if (urlString.endsWith(".class"))
{
File f = new File(url.getPath());
return new ClassFileIterator(f);
}
else if (!urlString.endsWith("/"))
{
return new JarFileIterator(url.openStream(), filter);
}
else
{
if (!url.getProtocol().equals("file"))
{
throw new ResourceReadingException("Unable to understand protocol: " + url.getProtocol());
}
File f = new File(url.getPath());
if (f.isDirectory() || url.getProtocol().toUpperCase().equals(AllowedProtocol.VFS.name()))
{
return new ClassFileIterator(f, filter);
}
else
{
return new JarFileIterator(url.openStream(), filter);
}
}
}
catch (MalformedURLException e)
{
throw new ResourceReadingException(e);
}
catch (IOException e)
{
throw new ResourceReadingException(e);
}
}
/**
* Gets the valid annotations.
*
* @return the valid annotations
*/
public List getValidAnnotations()
{
return validAnnotations;
}
/**
* Adds the valid annotations.
*
* @param annotation
* the annotation
*/
public void addValidAnnotations(String annotation)
{
this.validAnnotations.add(annotation);
}
/**
* Gets the annotation discovery listeners.
*
* @return the annotation discovery listeners
*/
public List getAnnotationDiscoveryListeners()
{
return annotationDiscoveryListeners;
}
/**
* Adds the annotation discovery listeners.
*
* @param annotationDiscoveryListener
* the annotation discovery listener
*/
public void addAnnotationDiscoveryListeners(AnnotationDiscoveryListener annotationDiscoveryListener)
{
this.annotationDiscoveryListeners.add(annotationDiscoveryListener);
}
/**
* Read.
*/
public abstract void read();
/**
* Gets the filter.
*
* @return the filter
*/
public abstract Filter getFilter();
/**
* Find resources.
*
* @return the uR l[]
*/
public abstract URL[] findResources();
/**
* Find resources.
*
* @return the uR l[]
*/
public abstract InputStream[] findResourcesAsStream();
/**
* Find resources by classpath.
*
* @return the uR l[]
*/
public abstract URL[] findResourcesByClasspath();
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ResourceIterator.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
import java.io.InputStream;
/**
* Interface for Resource Iterator, usually files.
*
* @author animesh.kumar
*/
public interface ResourceIterator
{
/**
* Please close after use.
*
* @return null if no more streams left to iterate on
*/
InputStream next();
/**
* Close.
*/
void close();
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ResourceReadingException.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.classreading;
import com.impetus.kundera.KunderaException;
/**
* Exception class for all exception scenarios involving resource reading.
*
* @author amresh.singh
*
*/
public class ResourceReadingException extends KunderaException
{
private static final long serialVersionUID = 2586557929464852258L;
/**
*
*/
public ResourceReadingException()
{
}
/**
* @param arg0
*/
public ResourceReadingException(String arg0)
{
super(arg0);
}
/**
* @param arg0
*/
public ResourceReadingException(Throwable arg0)
{
super(arg0);
}
/**
* @param arg0
* @param arg1
*/
public ResourceReadingException(String arg0, Throwable arg1)
{
super(arg0, arg1);
}
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/client/Client.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.client;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import com.impetus.kundera.generator.AutoGenerator;
import com.impetus.kundera.generator.Generator;
import com.impetus.kundera.graph.Node;
import com.impetus.kundera.index.IndexManager;
import com.impetus.kundera.loader.ClientFactory;
import com.impetus.kundera.persistence.EntityReader;
import com.impetus.kundera.persistence.context.jointable.JoinTableData;
/**
* In Kundera, Clients act as a translator of JPA calls to
* datastore-specific respective operations call. Clients are constructed via
* {@link ClientFactory} that are configurable in persistence.xml. This makes it
* possible for user to choose a {@link Client} implementation for a particular
* persistence unit.
*
* Client API defines methods that are required to be implemented by various
* clients implementations (Thrift, Mongo etc).
*
* Any new addition of datastore support must implement this API. This is
* because kundera-core - after initialization, caching etc, calls clients
* methods to read from/ write into datastores.
*
* @author vivek.mishra
*/
public interface Client
{
/**
* Retrieves an entity from datastore
*
* @param entityClass
* the entity class
* @param key
* The key of the row
* @return Entity object
*/
Object find(Class entityClass, Object key);
/**
* Retrieve columnsToSelect from multiple rows of a
* column-family.
*
* @param
* the element type
* @param entityClass
* the entity class
* @param columnsToSelect
* Array of column names that need to be populated into entity
* @param keys
* Array of row keys
* @return List of entity objects
*/
List findAll(Class entityClass, String[] columnsToSelect, Object... keys);
/**
* Finds entities that match a given set of embedded column values provided
* in the Map
*
* @param
* the element type
* @param entityClass
* the entity class
* @param embeddedColumnMap
* Map of embedded column name and their values that are used as
* a criteria for finding entities
* @return the list of entities
*/
List find(Class entityClass, Map embeddedColumnMap);
/**
* Cleans up client
*/
void close();
/**
* Removes an entity from datastore for a given primary key
*
* @param entity
* the entity
* @param pKey
* Primary key of entity to be deleted
*/
void remove(Object entity, Object pKey);
/**
* Gets the persistence unit.
*
* @return the persistence unit
*/
String getPersistenceUnit();
/**
* Gets the index manager.
*
* @return the index manager
*/
IndexManager getIndexManager();
/**
* Data node to persist entity with specific client.
*
* @param node
* data node.
*/
void persist(Node node);
void persistJoinTable(JoinTableData joinTableData);
/**
* Returns List of column values for given primary key and column name.
*
* @param
* Type cast
* @param schemaName
* Schema/Keyspace name.
* @param tableName
* Table/column family name.
* @param pKeyColumnName
* Primary key column name.
* @param columnName
* Name of column to be fetched.
* @param pKeyColumnValue
* primary key value.
* @return list of values fetched for
*/
List getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,
Object pKeyColumnValue, Class columnJavaType);
/**
* Returns array of primary key for given column name and it's value.
*
* @param schemaName
* Schema/Keyspace name.
* @param tableName
* table/column family name.
* @param pKeyName
* primary key column name.
* @param columnName
* column name to be used for search.
* @param columnValue
* value for parameterised .
* @param entity
* class entity class
* @return array containing fetched primary keys.
*/
Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
Object columnValue, Class entityClazz);
/**
* Delete rows from given table for given column name and corresponding
* value..
*
* @param schemaName
* Schema Name
* @param tableName
* Name of the table
* @param columnName
* Name of the column
* @param columnValue
* Name of column value
*/
void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue);
/**
* Find list of entities for given column name and column value, if index
* support is provided..
*
* @param colName
* the column name
* @param colValue
* the column value
* @param entityClass
* the entity class
* @return the list list of entities.
*/
List findByRelation(String colName, Object colValue, Class entityClazz);
/**
* Returns entity reader instance bind to specific client.
*
* @return reader entity reader.
*/
EntityReader getReader();
/**
* Returns query implementor class, required for initializing client
* specific query interface.
*
* @return class instance of configured query interface.
*/
Class getQueryImplementor();
/**
* Enables executing native script specific to a db client
*
*
* @param script
* @return
*/
Object executeScript(String script);
/**
* Gets the id generator.
*
* @return the id generator
*/
Generator getIdGenerator();
}
================================================
FILE: src/jpa-engine/core/src/main/java/com/impetus/kundera/client/ClientBase.java
================================================
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.kundera.client;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.impetus.kundera.db.RelationHolder;
import com.impetus.kundera.graph.Node;
import com.impetus.kundera.graph.NodeLink;
import com.impetus.kundera.graph.NodeLink.LinkProperty;
import com.impetus.kundera.index.IndexManager;
import com.impetus.kundera.metadata.KunderaMetadataManager;
import com.impetus.kundera.metadata.MetadataUtils;
import com.impetus.kundera.metadata.model.ClientMetadata;
import com.impetus.kundera.metadata.model.EntityMetadata;
import com.impetus.kundera.metadata.model.Relation;
import com.impetus.kundera.metadata.model.Relation.ForeignKey;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;
import com.impetus.kundera.property.PropertyAccessorHelper;
import com.impetus.kundera.utils.KunderaCoreUtils;
/**
* Base class for all Client implementations providing common utility methods to
* them all.
*
* @author amresh
*
*/
public abstract class ClientBase
{
/** The index manager. */
protected IndexManager indexManager;
/**
* @return the autoGenerator
*/
public String getAutoGenerator()
{
return this.getClientMetadata() != null ? this.getClientMetadata().getAutoGenImplementor() : null;
}
/** persistence unit */
protected String persistenceUnit;
protected boolean isUpdate;
protected ClientMetadata clientMetadata;
protected final KunderaMetadata kunderaMetadata;
protected final boolean showQuery;
protected Map externalProperties;
protected ClientBase(final KunderaMetadata kunderaMetadata, final Map properties,
final String persistenceUnit)
{
this.kunderaMetadata = kunderaMetadata;
this.externalProperties = properties;
this.persistenceUnit = persistenceUnit;
this.showQuery = KunderaCoreUtils.isShowQueryEnabled(properties, persistenceUnit, kunderaMetadata);
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.client.Client#getIndexManager()
*/
public final IndexManager getIndexManager()
{
return indexManager;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.client.Client#getPersistenceUnit()
*/
public String getPersistenceUnit()
{
return persistenceUnit;
}
/**
* Method to handle
*
* @param node
*/
public void persist(Node node)
{
Object entity = node.getData();
Object id = node.getEntityId();
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
isUpdate = node.isUpdate();
List relationHolders = getRelationHolders(node);
onPersist(metadata, entity, id, relationHolders);
id = PropertyAccessorHelper.getId(entity, metadata);
node.setEntityId(id);
indexNode(node, metadata);
}
public void remove(Object entity, Object pKey){
delete(entity, pKey);
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());
unIndexNode(metadata, entity,pKey);
}
protected void unIndexNode(EntityMetadata metadata, Object entity, Object pKey)
{
if(indexManager!=null)
{
indexManager.remove(metadata, entity, pKey);
}
}
/**
* @param node
* @return
*/
protected List getRelationHolders(Node node)
{
List relationsHolder = new ArrayList();
// Add column value for all parent nodes linked to this node
Map parents = node.getParents();
Map children = node.getChildren();
if (parents != null && !parents.isEmpty())
{
for (NodeLink parentNodeLink : parents.keySet())
{
String linkName = (String) parentNodeLink.getLinkProperty(LinkProperty.LINK_NAME);
Object linkValue = parentNodeLink.getLinkProperty(LinkProperty.LINK_VALUE) != null ? parentNodeLink
.getLinkProperty(LinkProperty.LINK_VALUE) : parents.get(parentNodeLink).getEntityId();
boolean isSharedByPrimaryKey = (Boolean) parentNodeLink
.getLinkProperty(LinkProperty.IS_SHARED_BY_PRIMARY_KEY);
Relation.ForeignKey multiplicity = parentNodeLink.getMultiplicity();
if (linkName != null && linkValue != null && !isSharedByPrimaryKey
&& multiplicity.equals(ForeignKey.ONE_TO_MANY))
{
RelationHolder relationHolder = new RelationHolder(linkName, linkValue);
relationsHolder.add(relationHolder);
}
}
}
// Add column value for all child nodes linked to this node
if (children != null && !children.isEmpty())
{
for (NodeLink childNodeLink : children.keySet())
{
String linkName = (String) childNodeLink.getLinkProperty(LinkProperty.LINK_NAME);
Object linkValue = childNodeLink.getLinkProperty(LinkProperty.LINK_VALUE) != null ? childNodeLink
.getLinkProperty(LinkProperty.LINK_VALUE) : children.get(childNodeLink).getEntityId();
boolean isSharedByPrimaryKey = (Boolean) childNodeLink
.getLinkProperty(LinkProperty.IS_SHARED_BY_PRIMARY_KEY);
Relation.ForeignKey multiplicity = childNodeLink.getMultiplicity();
if (linkName != null && linkValue != null && !isSharedByPrimaryKey)
{
if (multiplicity.equals(ForeignKey.ONE_TO_ONE) || multiplicity.equals(ForeignKey.MANY_TO_ONE))
{
RelationHolder relationHolder = new RelationHolder(linkName, linkValue);
relationsHolder.add(relationHolder);
}
else if (multiplicity.equals(ForeignKey.MANY_TO_MANY)
&& ((Field) childNodeLink.getLinkProperty(LinkProperty.PROPERTY)).getType()
.isAssignableFrom(Map.class))
{
Object relationTo = ((Node) children.get(childNodeLink)).getData();
RelationHolder relationHolder = new RelationHolder(linkName, relationTo, linkValue);
relationsHolder.add(relationHolder);
}
}
}
}
return relationsHolder;
}
/**
* @param node
* @param entityMetadata
*/
protected void indexNode(Node node, EntityMetadata entityMetadata)
{
if (indexManager != null)
{
if (!MetadataUtils.useSecondryIndex(getClientMetadata()))
{
Map